Wednesday, March 16, 2011

Firefox style onclick arguments in IE

In firefox when you add an onclick event handler to a method an event object is automatically passed to that method. This allows, among other things, the ability to detect which specific element was clicked. For example

document.body.onclick = handleClick;

function handleClick(e)
{
    // this works if FireFox
    alert(e.target.className);
}

Is there any way to approximate this in IE? i need to be able to detect which element is clicked from an event handler on the body element.

From stackoverflow
  • I think IE uses a variable called event. See if that works?

  • In IE it's

    e.srcElement
    
  • That is not the approved notation to add events to dom nodes.

    if (el.addEventListener){
      el.addEventListener('click', modifyText, false); 
    } else if (el.attachEvent){
      el.attachEvent('onclick', modifyText);
    }
    

    Is the recommended Notation for binding click events cross-browser friendly.

    See:

    Also, when an event is clicked, the callback function that is executed contains an object "this" which is the entity that was clicked.

    function foo() { 
       window.open(this.src, '_blank'); 
    }
    
    J-P : Obviously the Advanced event registration model has its benefits but for the most part people can just use the traditional notation. (One benefit of the traditional notation is that it plays nicer with screen readers)
  • Here is how would I do it in case I cannot use jQuery

    document.body.onclick = handleClick;
    
    function handleClick(e)
    {
        //If "e" is undefined use the global "event" variable
        e = e || event;
    
        var target = e.srcElement || e.target;
        alert(target.className);
    }
    

    And here is a jQuery solution

    $(document.body).click(function(e) {
      alert($(this).attr("class"));
    });
    
    J-P : In your jQuery example there is no point in passing the event.
    korchev : Yes, indeed. I am just passing it to show how it's done if needed.

0 comments:

Post a Comment