Event listeners on elements
Events are things that happen on a web page, like clicking on something, moving the mouse over an element, changing an element, and there are many more. We have seen how to add an onclick
event handler already. In the same way, you can add an onchange
handler, or an onmouseover
handler. There is one special condition, though; one element can only have one event handler as an HTML attribute. So, if it has an onclick
handler, it cannot have an onmouseover
handler as well. At this point, we have only seen how to add event listeners using HTML attributes like this:
<button onclick="addRandomNumber()">Add a number</button>
There is a way to register event handlers using JavaScript as well. We call these event listeners. Using event listeners, we can add multiple events to one element. This way, JavaScript is constantly checking, or listening, for certain events to the elements on the page. Adding event listeners is a two-step process...