Awesome Club

Event Listener Blog

How to use JavaScript event listeners

Event Listeners in JavaScript are essentially functions that execute when something happens.


Consider the following:

        
            window.addEventListener("load", (evt)=>{
                console.log("The window has loaded");
            })
        
    

The code shown above is known as an event listener. An Event listener takes an event and a function as paramater, then executes the function once the event takes place. In this scenario, the event listener is listening for "load" events and will execute the console log once the event happens. As you can imagine, this is a very useful tool as it is very easy to create responsiveness with an event listener.


There are numerous events that you can select and you can even create your own events. Here is a list of all HTML DOM Events


Event Listeners with various events


        
            window.addEventListener("click", (evt)=>{
                console.log("You clicked on the window");
            });
          
            const button = document.getElementById("button");
            button.addEventListener("click", (evt)=>{
                console.log("You clicked on the button");
            })
          
            button.addEventListener("mouseover", (evt)=>{
                console.log("You hovered over the button");
            })
        
    

JavaScript event listeners have some pretty simple functionality that can be extremely useful when used correctly.