Technology Networking & Internet

How to Create EventListener

    • 1). Add an element to the Web page. For this example, a button is used to change the text when the user clicks the object. Below is a simple example of an HTML button element.
      <button type="button">Click Me!</button>

    • 2). Create an EventListener on the button. The EventListener is added to the button and "listens" for user action. The following function binds a function to the button.
      function bindMyEventListener() {
      var myListener = document.getElementById("myButton");
      myListener.addEventListener("click", myBoundFunction, false);
      }

    • 3). Create the "myBoundFunction" code. In Step 2, a listener was bound to the button. In the "addEventListener" method, the "myBoundFunction" was listed as the function that triggers the code after the user clicks the button. The following function changes the button's text after the user clicks it.
      function changeText() {
      var myButton = document.getElementById("myButton");
      myButton.value = "Don't Click Me Anymore";
      }

    • 4). Add the function created in Step 2 to the Web page's "onload" event. The onload event is used to load code when the user opens the Web page. The EventListener needs to be bound when the page loads, so this is necessary or nothing will happen when the user clicks the button. The following is an example of how to load a function:
      <body onload="bindMyEventListener();">



Leave a reply