DOM :: Event Listener in JavaScript
Adding Events Handlers
Method | Description |
---|---|
document.getElementById(id).onclick = function(){code} | Adding event handler code to an onclick event |
Adding Event Listener
The addEventListener()
method attaches an event handler to the specified element.The addEventListener()
method attaches an event handler to an element without overwriting existing event handlers.
You can add many event handlers to one element.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener()
method makes it easier to control how the event reacts to bubbling.
When using the addEventListener()
method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener()
method.
addEventListener()
method attaches an event handler to the specified element.addEventListener()
method attaches an event handler to an element without overwriting existing event handlers.addEventListener()
method makes it easier to control how the event reacts to bubbling.addEventListener()
method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.removeEventListener()
method.The first parameter is the type of the event (like "click
" or "mousedown
" or any other HTML DOM Event.
<body> <button id="myBtn">Try it</button> <script> function myFunction() { alert ("Hello World!"); } document.getElementById("myBtn").addEventListener("click", myFunction); </script> </body>
Add Alert Date :: with addEventListener
<body>
<button id="dte">Date is..</button>
<script>
var today = new Date(); document.getElementById("dte").addEventListener("click",function(){ alert(today); })
</script> </body>
onSubmission with addEventListener