Extract Elements

We include our ‘core’ library, in the header


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

As with the previous example, 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(e)
    {
      var el = ssExtractEl(e);
      alert("You have clicked on: " + el.innerHTML);
      return ssStopTheRest(e);
    }

    ssAddLoadEvent(preparePage);
          
  • However, in addition, showAlert now has a parameter (e) which provides access to the element clicked. Using ssExtractEl(e) within the function we can access all the current properties of that element. To illustrate this the innerHTML of the links are randomised every couple of secondd, and subsequently clicking that link will show the current value.
  • We attach the event without declaring any parameters using ssAddEvent(anchors[aCount], "click", showAlert, false); and define the function with a parameter showAlert(e). This is a very powerful and reliable technique.
  • We also include return ssStopTheRest(e); in the definition of showAlert, which does two things
    • It prevents the click event from ‘bubbling up’ through the DOM (e.g. click events attached to the body will not be run).
    • It will return false, which cancels the default behaviour of the browser (i.e. it won’t follow the hyperlink #).
  • As well as giving us access to the properties of the element, ssExtractEl(e) also gives us access to extended properties of the event (e.g. if it was a keypress instead of a click, we can extract which key was pressed).
  • We sometimes need to take into account the fact that an element may contain child nodes which could be clicked, the most common example being an image within a hyperlink, in which case we use this syntax
    
        if (el.nodeName.toLowerCase() == "img")
        {
          el = el.parentNode;
        }