Ways to execute multiple event handlers for a single event in Javascript
Its a common situation in any application, where you want multiple functions to be executed with a button click or a change event. Its important to neatly handle this to avoid errors.
Say you have a button and you would like 2 functions to execute on clicking it.
There are 3 ways I would like to share to handle this scenario.
- Call a function which in turn calls the 2 functions you want to execute using promises.
<button onclick=”handler()” id=”button1"></button>
handler() is the function called when the click event registers. handler1() and handler2() need to be executed within handler().
<script>
function handler1(){
const promise1=new Promise(function(resolve,reject)
{
resolve(“handler1”);
})
return promise1;
}function handler2(){
const promise2=new Promise(function(resolve,reject)
{
resolve(“handler2”);
})
return promise2;
}function handler(){
handler1()
.then(result=>{console.log(result);return handler2()})
.then(res=>console.log(res))
.catch(err=>console.log(err));}
</script>
As you can see, we can use promises to acheive this task. handler1() and handler2() execute in sequence.
handler1() and handler2() both return promises which can be resolved in case of success or rejected in case of errors. In applications, it definitely wont be so easy to write due to the complexity of the tasks involved in each event handler but it ensures that the functions are executed one after another in a neat way.
2. The 2nd way is to call the 2 functions using the onclick attribute directly.
<button onclick=”handler1();handler2()” id=”button1">Click</button>
Script:
<script>function handler1()
{
console.log(“handler1”);
}function handler2()
{
console.log(“handler2”);
}</script>
3. The 3rd way is to use addEventListener to add many events of the same type to an element.
<button id=”button1">Click</button>
Script:
<script>function handler1()
{
console.log(“handler1”);
}function handler2()
{
console.log(“handler2”);
}document.getElementById('button1').addEventListener('click',handler1,false);
document.getElementById('button1').addEventListener('click',handler2,false);</script>
The 2 functions execute in the same order in which the addEventListener() is called.3rd argument:false indicates bubbling method of event propagation.
In any kind of event handling its very important to take care of event propagation i.e event bubbling and event capturing.
If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element’s “click” event should be handled first?
In bubbling the inner most element’s event is handled first and then the outer: the <p> element’s click event is handled first, then the <div> element’s click event.
In capturing the outer most element’s event is handled first and then the inner: the <div> element’s click event will be handled first, then the <p> element’s click event.