Tuesday, December 14, 2010

Four Ways Javascript Binding Event Listeners

There is several ways in how to bind an event in Javascript. As far as I know four ways exist on behalf of binding a Javascript event. Here brief description of each way
1. Through inline HTML Code

The Javascript event declared inline in HTML code, for example:
<input type=”button” value=”Alert Message” onclick=”showAlert()” />
Then showAlert() is a Javascript function that merely show an alert message:
function showAlert()
{
      window.alert("Hello, World!!!");
}
This inline event binding works for all browsers.
2. Traditional Binding

I think this way is more elegance than the first one, but before we can do this we must get the desired element. We can use two useful methods of document object to get the element we want, there is getElementById() and getElementsByTagName(). Both method receive one string parameter which show the ID of an element (for getElementById()) or elements name (for getElementsByTagName()). Please aware that the result of getElementsByTagName() is always array of element.

Suppose that we have the following page:

    <html>
       <head>
          <title>Events Binding</title>
          <script lang="javascript" type="text/javascript">
          var txtContent;
    
          window.onload = function()
          {
             txtContent = document.getElementById("txtContent");
             txtContent.onfocus = txtFocusHandler;
             txtContent.onblur = txtBlurHandler;
    
             var all = document.getElementsByTagName("li");
             for (var i=0;i<all.length;i++) {
                all[i].onmouseover = liMouseOverHandler;
                all[i].onmouseout = liMouseOutHandler;
                all[i].onclick = liClickHandler;
            }
        };
    
       function txtFocusHandler(e)
       {
          e= e||window.event;
          var trgSrc = e.target||e.srcElement;
          trgSrc.style.backgroundColor = "gainsboro";
       }
    
       function txtBlurHandler(e)
       {
          this.style.backgroundColor = "white";
       }
    
       function liMouseOverHandler()
       {
          this.style.backgroundColor = "#EFEFEF";
       }
    
       function liMouseOutHandler()
       {
          this.style.backgroundColor = "white";
       }
    
       function liClickHandler(e)
       {
          e = e||window.event;
          var liElm = e.target||e.srcElement;
          var text = liElm.firstChild.nodeValue;
    
          txtContent.value = text;
       }
       </script>
    </head>
    <body>
       <form id="frm">
          Content: <input type="text" id="txtContent" width="200px" />
          (Hover the elements below and click one of it)
          <p>
          <ul>
             <li>Martial Arts, Swimming, Football, Basketball, Badminton</li>
             <li>Work, Office, Vacation, Holiday</li>
             <li>Computer, Internet, Blogging</li>
          </ul>
       </form>
    </body>
    </html>

For simplicity I mix the HTML and Javascript code (although it maybe looks messy). The above code will produce a TextBox element and three <li> element. Hover the <li> element and click it will copy paste the nodeValue of <li> element to TextBox.
Hover
Traditional binding works well for all browser.
3. W3C Binding

W3C binding works on browsers that comply with W3C standard. We need to remember one important method when attach event using W3C binding: addEventListener(). This method receives three parameters, first parameter is event name (such as: click, load, mouseout, etc.), second parameter is function that handle it, and third parameter is boolean values (true for event capturing or false for event bubbling).

Look at the following simple example on how to use addEventListener():
    <html>
       <head>
          <title>Test W3 Binding</title>
          <script lang="javascript" type="text/javascript">
          window.onload = function()
          {
             var elJ = document.getElementsByTagName("li");
             for (var i=0;i<elJ.length;i++) {
             elJ[i].addEventListener('mouseover',liMouseOver,false);
             elJ[i].addEventListener('mouseout',liMouseOut,false);
          }
       };
    
       function liMouseOver()
       {
          this.style.backgroundColor = "gainsboro";
       }
    
       function liMouseOut()
       {
          this.style.backgroundColor = "white";
       }
       </script>
    </head>
    <body>
       <ul>
          <li>First Element</li>
          <li>Second Element</li>
          <li>Third Element</li>
       </ul>
    </body>
    </html>

Run the code in W3C compliant browsers and hover the mouse cursor above an <li> element and you will see the background color of <li> element changed.
4. IE Binding

As usual, Internet Explorer (IE) has its own way on binding an event. Remember this method when binding an event using IE binding: attachEvent(). This methods receives two parameters, first parameter is event precede with ‘on’ word (such as: onclick, onload, onmouseout), the second parameter is function that handle it.

If we want do the same thing (hover and out mouse effect) in IE way we can do with this code:
    <html>
      <head>
        <title>Test IE Binding</title>
        <script lang="javascript" type="text/javascript">
        window.onload = function()
        {
          var allLi = document.getElementsByTagName("li");
    
          for (var i=0;i<allLi.length;i++) {
            allLi[i].attachEvent('onmouseover',liMouseOver);
            allLi[i].attachEvent('onmouseout',liMouseOut);
          }
        };
    
        function liMouseOver()
        {
          var e = window.event;
          var elm = e.srcElement;
          elm.style.backgroundColor = "gainsboro";
        }
    
        function liMouseOut()
        {
          var e = window.event;
          var elm = e.srcElement;
          elm.style.backgroundColor = "white";
        }
        </script>
      </head>
      <body>
        <ul>
          <li>First Element</li>
          <li>Second Element</li>
          <li>Third Element</li>
        </ul>
      </body>
    </html>

We must notice that this keyword inside a event handler function in IE point to window object not the current element, so we need a little more effort to achieve our goal. It something looks like this:



function liMouseOver()

{

var e = window.event;

var elm = e.srcElement;

elm.style.backgroundColor = "gainsboro";

}

Run the code in the browser and we should get the same result as before.

http://triaslama.wordpress.com/2008/07/22/four-ways-javascript-binding-event-listeners/

No comments: