Fire A Click Event In Raw Javascript
In jQuery I can do something like: $('#example').click(); What is the equivalent in raw Javascript? I have tried the following: document.getElementById('example').click(); But th
Solution 1:
I use this in my framework:
functionfireEvent() {
var eventType = null, i, j, k, l, event,
einstellungen = {
'pointerX': 0,
'pointerY': 0,
'button': 0,
'ctrlKey': false,
'altKey': false,
'shiftKey': false,
'metaKey': false,
'bubbles': true,
'cancelable': true
}, moeglicheEvents = [
['HTMLEvents', ['load', 'unload', 'abort', 'error', 'select', 'change', 'submit', 'reset', 'focus', 'blur', 'resize', 'scroll']],
['MouseEvents', ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mousemove', 'mouseout']]
];
for(i=0,j=moeglicheEvents.length;i<j;++i) {
for(k=0,l=moeglicheEvents[i][1].length;k<l;++k) {
if(arguments[1] === moeglicheEvents[i][1][k]) {
eventType = moeglicheEvents[i][0]; i = j; k = l;
}
}
}
if(arguments.length > 2) {
if((typeofarguments[2]) === 'object') {
change(einstellungen, arguments[2]);
}
}
if(eventType === null) {
thrownewSyntaxError('Event type "' + arguments[1] + '" is not implemented!');
}
if(document.createEvent) {
event = document.createEvent(eventType);
if(eventType === 'HTMLEvents') {
event.initEvent(arguments[1], einstellungen.bubbles, einstellungen.cancalable);
} else {
event.initMouseEvent(arguments[1], einstellungen.bubbles, einstellungen.cancelable, document.defaultView,
einstellungen.button, einstellungen.pointerX, einstellungen.pointerY, einstellungen.pointerX, einstellungen.pointerY,
einstellungen.ctrlKey, einstellungen.altKey, einstellungen.shiftKey, einstellungen.metaKey, einstellungen.button, arguments[0]);
}
arguments[0].dispatchEvent(event);
} else {
einstellungen.clientX = einstellungen.pointerX;
einstellungen.clientY = einstellungen.pointerY;
event = document.createEventObject();
event = extend(event, einstellungen);
arguments[0].fireEvent('on' + arguments[1], event);
}
}
argument 1 is the element, the second argument the event, the third (optional) options.
Sorry, i forgot to rewrite some parts:
_.isObject()
to (typeof arguments[2]) == 'object'
and _.change
to change and this function is needed:
functionchange() {
var name;
for(name inarguments[1]) {
if((typeofarguments[1][name]) === 'object') {
if((typeofarguments[0][name]) === 'undefined') {
arguments[0][name] = {};
}
change(arguments[0][name], arguments[1][name]);
} else {
arguments[0][name] = arguments[1][name];
}
}
returnarguments[0];
};
Edit:
In your case it would be fireEvent(document.getElementById('example'), 'click');
Post a Comment for "Fire A Click Event In Raw Javascript"