Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
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.
element.addEventListener({event}, {function}, {useCapture});
//anonymous function
//document.getElementById("TestButton").addEventListener("click", function () { alert("Hello World!"); });
// calling functions
document.getElementById("TestButton").addEventListener("click", function(){ SayHello(); SayGoodBye(); });
function SayHello()
{
let demo1 = document.getElementById("demo1");
demo1.innerHTML = "Hello World";
}
function SayGoodBye()
{
let demo1 = document.getElementById("demo2");
demo1.innerHTML = "Good bye World";
}
// other examples
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
You can also remove an event listener by using removeEventLister()
.
element.removeEventListener("mousemove", myFunction);
http://www.w3schools.com/js/js_htmldom_eventlistener.asp