CSE 154 Examples

Add Event Listener

Description :

The Add Event Listener is used in Javascript to attach event handlers to events. If we have an event listener attached to a DOM element that listens for a specific event (the "click event") for example, every time we click on the DOM element, our event Listener will catch the event and execute the JS code we want it to.

Syntax for addEventListener:

              
                let domElement = document.getElementById("some_id");
                domElement.addEventListener("event_name", function_to_call_in_case_of_event);
              
            

Exercise :

This is the code used for the button : <button id="button-1"> Text 1 </button> Originally the "Text 1" button has no event listener attached to it. However we can attach an event listener quite easily.

Here's another button: <button id="button-2"> Click to add an Event Listener to Button-1 </button> Click on the second button to now attach an event listener to the "Text 1" button.

On the event of a click on button-1 now, the following code will execute which changes the text of the "Text 1" button:

          
              let button = document.getElementById("button-1");
              button.addEventListener("click", changeText);

              function changeText() {
                let button = document.getElementById("button-1");
                button.innerText = "Changed Text!"; //This changes the text of the "Text 1" Button
              }