Introduction
In this tip, we see how to trigger an event manually in plain vanilla JavaScript and how to do it in Internet Explorer which is different from others. Let's see that by making a simple example triggering a button event on window load using plain vanilla JavaScript.
Background
We get to few requirements where we need to trigger events manually after some pre processing in other events, so that we reduce code redundancy to rewrite the same trigger event code in same function rather we trigger manually that event which does the same work. Triggering events manually is a bit different in Internet Explorer from others, so we need to handle both to make our web application have same the experience across browsers. You can use jQuery to reduce browser redundancies. But in this tip, we see how to trigger using JavaScript across browsers.
Example
Let us have a button in our website which on click writes a welcome message in the document. But let's trigger it on window load event and manually trigger the button event.
In all other browsers, we initialize mouse event by instantiating a new MouseEvent(. , .)
. Internet Explorer doesn't support MouseEvent
action. It throws an action not supported error. To initialize a mouse event, we need to follow two steps:
- Create a new event for document.
- And initialize a mouse event on that created object.
For Internet Explorer (Which also works for Firefox)
var event = document.createEvent("MouseEvent");
event.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
For others browsers, we just instantiate a new MouseEvent
as below: (Non IE)
var event = new MouseEvent("click",{
'view': window,
'bubbles': true,
'cancelable': true
});
The last step is the same for all browsers to trigger an event manually as follows (for all browsers including Internet Explorer):
myButton.dispatchEvent(event)
The initMouseEvent
method has many arguments, we mostly care about few, the eventType
that is click
in this case, the 2nd one is canBubble
which is true
so the event propagates upward, canCancelable
i.e., default action can be canceled, fourth one is the view, i.e., is the current window. We don't use the rest much so let them have the same as the above values. You can get more context about initMouseEvent
here.
HTML
<button id="myButton">Greet User</button>
JavaScript
window.onload=function(){
var event;
var myButton = document.getElementById("myButton");
myButton.addEventListener("click",function(){
document.write("Hello guest ! Welcome ? ");
},false);
if(document.createEvent){
event = document.createEvent("MouseEvent");
event.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
}
else{
event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
}
myButton.dispatchEvent(event);
};
The above function on window load will trigger button click event and shows a popup.
Here's code pen demo.
Thanks for reading. :)