Read, With the Name of Your Lord Who Created

Four Ways Javascript Binding Event Listeners

Posted by triaslama on July 22, 2008

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.

About these ads

17 Responses to “Four Ways Javascript Binding Event Listeners”

  1. If you put another element in the LI for example: >li<First Element>/li<, the fourth way (IE) will make the word Element (the EM node) gray when hovering. With the third way the whole LI will get gray. Do you know a good fix?
    I tought about deleting the onclick handlers from childnodes or checking if the srcElement’s nodeName is equal to “LI”. But maybe there is a better way?

  2. Sorry, > should have been < and vice-versa.

  3. gbfszqpt lqkm rcugsyjn ysnkp xcsklenzm biftudam hvmpbd

  4. Peter said

    I appreciate the article, but the title is very confusing. I was hoping for something on using bind() (that is, binding) for event listeners. This is a question of variable scope I’m working on.

    • If you are not worried about browser support, there is a way to rebind the ‘this’ reference in the function called by the event. It will normally point to the element that generated the event when the function is executed, which is not always what you want. The tricky part is to at the same time be able to remove the very same event listener, as shown in this example: http://jsfiddle.net/roenbaeck/vBYu3/

  5. Peter said

    Whoops, sorry about the previous comment, you can delete it. I was thinking prototype framework! yikes.

  6. martial art styles…

    Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created…

  7. Adult Gadget Fun — Special expertise as well as wonderful collection of adult sex toys…

    […]Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created[…]…

  8. bio vitamins…

    […]Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created[…]…

  9. Goede software hoeft niet duur te zijn…

    […]Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created[…]…

  10. DIPU said

    Thank you, Crystal Clear explanation

  11. fichersek said

    “Traditional Binding”: I know that “the DOM” defines the way in which HTML document objects are exposed to your script.
    Document Object Model (DOM), is standardized by the World Wide Web Consortium (W3C).
    Where in W3C standard documents says about “Traditional Binding”? I mean, I know “onclick” is defined in the “HTML 4.01 Specification” (W3C), but as an attribute (), not as a DOM Property (DOMObj.onclick=myfunction;).
    Is it clear my question? sorry for my english.

  12. goverdhan said

    If I use W3C Binding then will it work in all the browsers or do I have to handle the browser compatibility separately for event handling?

  13. Thanks a lot.It’s useful for me.

  14. Nagu said

    Thank u. Nice it helps me a lot

  15. comment faire une machine a sous en lego

    Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created

  16. slot machine bonus caveman

    Four Ways Javascript Binding Event Listeners « Read, With the Name of Your Lord Who Created

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: