Functions of JavaScript Event Listener
Functions of Event and Event handlers
Events are nothing but it is an action which manipulates the page in the browser when the user performs any operations in it. They plays a vital role because they cause elements of webpages to change dynamically.
Let’s see an example so that you will understand.
- The load event occurs when the browser finishes loading the document.
- The click event occurs when the user clicks the button in the webpage.
There are many event can be happen either once or multiple times. You may not know exactly when an event will happen, especially when an user is generated.
The addEventListener() method provides an event handler in JavaScript. This can be attached to the HTML element. You can able to attached more than one event handler in JavaScript.
addEventListener() Syntax
The syntax for addEventListener() is:
target.addEventListener(event, function, useCapture)
- target- it is used to add your event handler to the HTML element. It is a part of Document Object Model (DOM).
- event- it is a string which is used to specify the name of the event. We already seen this in load and click event.
- function- it is a function used to run when the event is detected. This is main reason your webpages changes dynamically.
- useCapture- it is a optional boolean (true or false) value used to specify whether the event is executed in the phase. This value determines which values has to executed first in nested HTML element. By default it set to false that means the innermost HTML element is executed first.
Passing Event as a Parameter
Sometimes we want to know more information about the event when it was clicked. For that we have to pass an event parameter to our function.
Let’s see an example how we can implement this.
button.addEventListener('click', (e)=>{
console.log(e.target.id)
})
From the above example, the event parameter is a variable named e bit it can easily called anything else such as event. This is a parameter of an object contains various information about the event such as target id.
You don’t have to add any special function. JavaScript itself automatically know what to do when you pass parameter in the function.
Removing Event Handlers
For some reasons you don’t want an event handler to activate, then removes it by following code.
target.removeEventListener(event, function, useCapture);The parameters are the same as addEventListener().
Conclusion
I hope you enjoyed a lot and find something new today. The best way to get better in event handlers is to practice more and apply this concept in your projects.
Have fun and thanks for reading!
Comments
Post a Comment