YouTip LogoYouTip

Js Htmldom Eventlistener

# JavaScript HTML DOM EventListener * * * ## The addEventListener() Method ## Example Trigger an event listener when the user clicks a button: document.getElementById("myBtn").addEventListener("click", displayDate); [Try it Yourself Β»](#) The addEventListener() method is used to attach an event handler to an element. The addEventListener() method does not overwrite existing event handlers. You can add multiple event handlers to one element. You can add multiple event handlers of the same type to one element, e.g., two "click" events. You can add event listeners to any DOM object, not just HTML elements. e.g., the window object. The addEventListener() method makes it easier to control how the event reacts to bubbling and capturing. When using the addEventListener() method, JavaScript separates HTML from JavaScript, making the code more readable, and allowing adding event listeners even when you don't control the HTML markup. You can use the removeEventListener() method to remove an event listener. * * * ## Syntax _element_.addEventListener(_event, function, useCapture_); The first parameter is the type of the event (e.g., "click" or "mousedown"). The second parameter is the function to be called when the event occurs. The third parameter is a boolean value that describes whether the event should be executed in the capturing or the bubbling phase. This parameter is optional. | ![Image 2: Note](#) | Note: Do not use the "on" prefix. For example, use "click" instead of "onclick". | | --- | * * * ## Adding an Event Handler to an Element ## Example Alert "Hello World!" when the user clicks on an element: _element_.addEventListener("click", function(){ alert("Hello World!"); }); [Try it Yourself Β»](#) You can refer to an external function by its name: ## Example Alert "Hello World!" when the user clicks on an element: _element_.addEventListener("click", myFunction); function myFunction() { alert ("Hello World!"); } [Try it Yourself Β»](#) * * * ## Adding Multiple Event Handlers to the Same Element The addEventListener() method allows you to add multiple events to the same element, without overwriting existing events: ## Example _element_.addEventListener("click", myFunction); _element_.addEventListener("click", mySecondFunction); [Try it Yourself Β»](#) You can add events of different types to the same element: ## Example _element_.addEventListener("mouseover", myFunction); _element_.addEventListener("click", mySecondFunction); _element_.addEventListener("mouseout", myThirdFunction); [Try it Yourself Β»](#) * * * ## Adding an Event Handler to the Window Object The addEventListener() method
← Met Element RemoveeventlisteneMet Element Addeventlistener β†’