Attach Events

We include our ‘core’ library, in the header


    <script src="../Include/Core.js" type="text/javascript"></script>
          

We then include the following code, so that when the page loads, it loops through all a elements within #main and attaches the event showAlert() to run when any of these are clicked.


    function preparePage()
    {
      var anchors = document.getElementById("main").getElementsByTagName("a");
      for (var aCount=0; aCount != anchors.length; aCount++)
      {
        ssAddEvent(anchors[aCount], "click", showAlert, false);
      }
    }

    function showAlert()
    {
      alert("You have clicked on a team.");
    }

    ssAddLoadEvent(preparePage);
          
  • All the code is included in the <head>, and so cannot be run straight away as the rest of the document has not yet loaded. We thus wrap everything up in the function preparePage() and set this to be run when the page is loaded using ssAddLoadEvent(preparePage);
  • The two lines
    var anchors = document.getElementById("main").getElementsByTagName("a");
    and
    for (var aCount=0; aCount != anchors.length; aCount++)
    are bog standard, and together with ssHasClass() getElementsByTagName() (which will be introduced shortly), nothing else should be needed to locate all the appropriate items in the page.
  • We attach the funtion showAlert to be run when a hyperlink (anchors[aCount]) is clicked using our generic event attaching function ssAddEvent, which is used as follows
    ssAddEvent(anchors[aCount], "click", showAlert, false);
  • Note that when you click on a link, the href (# in this case) is followed, as we are not doing anything to stop the default behaviour of the browser after our click event takes place.
  • There is also a function ssRemoveEvent() which removes events which have been attached - it takes the same arguments as ssAddEvent(), but we don’t use it much.