Javascript: / Home / AddEvent

Adding an Event

Event handlers can be assigned to an element in a script function instead of adding them with an inline event. Notice the AddEvents() function call at the end of the <body> element.

The addEventListener() method of the target element is used to make the assignment.

    <head>
      <script>
        // Adds the required event handler assignment.
        function AddEvents()
        {
          pageTitle.addEventListener("click", TitleClick);
        }

        // The title click event handler.
        function TitleClick()
        {
          alert("Title was clicked.");
        }
      </script>
    </head>
    <body>
    // Elements are added by "id" name to the DOM windows object.
    <h3 id="pageTitle">Adding an Event</h3>
    <script>AddEvents();</script>
  </body>
<- ExternalScript            OldStyleDeclarations ->
8AddEvent