Tallaght Campus

Department of Computing

Javascript Event Handlers - Dynamic Setup from Code

Download exercise file bundle

    So far we have learnt one method for setting up event handlers - with an event handler property on the HTML element (for example onclick). Another way to set up an event handler is programmatically from Javascript code. This method of setting up handlers is the topic of this tutorial.

  1. The addEventListener() method

    The addEventListener() method

    • The exercise file bundle includes two files: eh2.html and eh.js and eh2.js is included as a script in this HTML document. Open the file eh2.js in a text editor and examine it. The file contains a function called changeBodyColour(). The function randomly changes the page background colour when called.
    • Open the HTML file in a text editor and examine it. The button does not have an event handler property and, accordingly, when the HTML page is opened in a browser and the button is clicked, nothing happens. Try this.
    • Now we will run a Javascript instruction that will assign the function changeBodyColour() as event handler to the button. With eh2.html open in the browser, open the console and execute the following line of code:
      document.getElementById("chgbdycol").addEventListener("click", changeBodyColour);

      The method addEventListener sets a function as an event handler for the object it is called on. It takes two arguments:

      • the name of the event as a string (e.g. "click")
      • the name of the function that is to become a handler for the event

      This has the same effect as if the handler were set in HTML:

      <button id="chgbdycol" type="button" onclick="changeBodyColour();">Change page background</button>
    • Click on the Change page background button a few times to test that the handler has been set up.
  2. Setting up the handler at page-load time

    Setting up the handler at page-load time

    • To make the handler more permanent, we can add the line that sets the handler into the file eh2.js. This results in the line being executed at page-load time.
    • Copy the following line (it is the same as the one we ran in the console previously) into eh.js, as the last line in that file:
      document.getElementById("chgbdycol").addEventListener("click", changeBodyColour);
    • Reload page eh2.html and check that the button is working (without the handler having to be set from the console).
  3. Setting up the handler from inside another handler

    Setting up the handler from inside another handler

    • We now comment out the line in eh2.js that sets up the click handler at load time.
    • We create another button called 'Activate change page background button' and set it up with a click handler function called activateCPBButton.
    • The function activateCPBButton now needs to be defined to set up the handler on the button 'Change page background'. How? By adding to it the same line of code we used twice already, but this time into the function body:
      document.getElementById("chgbdycol").addEventListener("click", changeBodyColour);
    • We reload the page and test. What should happen is:
      • Click button Change page background - nothing happens
      • Click button Activate change page background button
      • Click button Change page background again - the colour of the background should change
  4. Removing the handler

    Removing the handler

    • Let's create another button, called 'Deactivate change page background button' and set it up with a click handler function called deactivateCPBButton.
    • The following code removes the event listener. We add it into the 'deactivate' function.
      document.getElementById("chgbdycol").removeEventListener("click", changeBodyColour);
    • Test by reloading the page and activating, then deactivating the 'Change page background' button, always checking if the activation/deactivation has actually worked.
  5. Adding a handler with a parameter

    Adding a handler with a parameter

    The second argument that needs to be passed into the addEventListener() method is a handler function with no parameters. In the examples above we needed to set the function changeBodyColour as handler and it met this requirement. To add a function with parameters, we need to wrap it in a function without parameters.

    • We add yet another button to our HTML file: 'Make background red', with id 'makered'.
    • We want to set the function changeBodyToSpecifiedColour as the handler by calling addEventListener, but adding it directly is not possible because changeBodyToSpecifiedColour takes an argument and addEventListener needs to be given a function that does not take arguments.
    • To solve this problem, we use an anonymous function without arguments, from which we call changeBodyToSpecifiedColour, passing in 'red' for the argument:
      document.getElementById("makered").addEventListener("click", function() { changeBodyToSpecifiedColour("red"); });
      We add this handler-setup code at the end of the file eh2.js
    • Reload the HTML page and test that clicks on the button 'Make background red' have the desired effect.
  6. Adding an array of handlers

    Adding an array of handlers

    • Insert the following html snippet into the HTML file, below the last button:

      <hr>
      <button class="gb">
          <h4>One</h4>
      </button>
      
      <button class="gb">
          <h4>Two</h4>
      </button>
      
      <button class="gb">
          <h4>Three</h4>
      </button>
      
      <p></p>
    • We want to write some code so that when the first button is clicked the text "I am button number 1 and my name is One" appears in the paragraph element. Analogous text should appear when the other two buttons are clicked.
    • The behaviour is practically the same for the three buttons, which means we can use one function.
    • As the text varies from button to button, we know that the function has to have a parameter.
    • The code should iterate through the buttons to set the same handler but with a different number as parameter.
  7. Alternative: setting the event handler property directly

    Alternative: setting the event handler property directly

    • An alternative programmatic construct for setting event handlers is their direct assignment to event handler properties of elements.
    • Similarly, a handler can be removed by setting the event handler property to undefined.
    • We will demonstrate this by adding a handler for clicks on button Make background a random colour (once), which changes the background to a random colour and then removes itself as handler.

Download completed exercises