The solution in JavaScript can be obtained as follows:
function fireEvent(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt);
}
}
This function accepts two parameters, the target element and the event to be triggered on that target element.
Example also in JSFiddle .
Example
Below is an example of usage where we have a alert()
in the first element, the second element to make use of the function presented above so that when it receives a click, the click event of the first element is triggered :
function fireEvent(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt);
}
}
<div id="meuElemento" onclick="alert('bubu');">
Se clicares aqui dá um alert()
</div>
<div onclick="fireEvent(document.getElementById('meuElemento'), 'click');">
Se clicares aqui, vai despoletar o clique no elemento que tem o alert()
</div>
Documentation
Documentation on the method dispatchEvent()
and on method fireEvent()
of Internet Explorer:
-
Method fireEvent
Triggers the event specified in the object.
-
Method dispatchEvent
It triggers an event on the specified target element, invoking the affected eventlisteners in the appropriate order. Normal event processing rules (including capture and optional bubble phase) apply to manually triggered events with dispatchEvent()
.
Note:
For more in depth, please refer to the documentation on Document Object Model Events the EventTarget
interface, introduced in DOM level 2, where it explains the purpose of this interface as well as its operation in greater detail.
Function code originally posted in Firing Javascript Events (like onchange) jehiah.cz which was published by @jehiah on 2008-01-23, and was subsequently optimized this of the published SOEN by @Chris MacDonald.