0

my problem here:why doesn't this code work ????? ... the message doesn't appear

i'm trying to add event listener to element x on event click

    function test()
    {
    alert("test");
    }

var EventsCrossBrowsers = 
 {
    addEvents:(function(element,event,func)
              {
                    if(element.addEventListener)
                    {
                        return elemenet.addEventListener(event,func,false);
                    }
                    else if(elemenet.attachEvent)
                    {
                        return elemenet.attachEvent("on"+event,func);
                    }
              }());
 }

 var x =document.getElementById("test");

EventsCrossBrowsers.addEvents(x,"click",test);

thanks alot jfriend00.... the most smiple way i think :-

function test()
{
    alert("test");
}

function addEventsCrossBrowsers(elemenet,event,func)
{
    if(elemenet.addEventListener)
    {
        elemenet.addEventListener(event,func,false);
    }
    else if(elemenet.attachEvent)
    {
        elemenet.attachEvent("on"+event,func);
    }
}
var x =document.getElementById("test");
addEventsCrossBrowsers(x,"click",test);

your second way is almost the same except i don't understand the return ... thank you again...

  • 7
    Mohamed, your question is being downvoted, and is likely to be closed, because you haven't told us what "doesn't work" means. Do you get an error message? Does nothing happen at all? Does a big block of cheese fall through your roof whenever you execute this? Read [this helpful page](http://stackoverflow.com/questions/how-to-ask). – Michael Petrotta Apr 14 '12 at 00:35
  • 5
    A big block of cheese falling through the roof is not a bug if crackers are included. – madth3 Apr 14 '12 at 01:26

1 Answers1

15

In your function, I see you are using both elemenet and element where they should be the same spelling. That would be at least part of the problem.

I also see that your addEvents function is a self executing function which doesn't make sense in this regard. It seems like it should just be a normal function.

Here's my cross browser event function. In addition to make one function for adding event handlers, it also normalizes the this pointer and the events object so they can be treated the same in any browser too.

// add event cross browser
function addEvent(elem, event, fn) {
    // avoid memory overhead of new anonymous functions for every event handler that's installed
    // by using local functions
    function listenHandler(e) {
        var ret = fn.apply(this, arguments);
        if (ret === false) {
            e.stopPropagation();
            e.preventDefault();
        }
        return(ret);
    }

    function attachHandler() {
        // set the this pointer same as addEventListener when fn is called
        // and make sure the event is passed to the fn also so that works the same too
        var ret = fn.call(elem, window.event);   
        if (ret === false) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        }
        return(ret);
    }

    if (elem.addEventListener) {
        elem.addEventListener(event, listenHandler, false);
        return {elem: elem, handler: listenHandler, event: event};
    } else {
        elem.attachEvent("on" + event, attachHandler);
        return {elem: elem, handler: attachHandler, event: event};
    }
}

function removeEvent(token) {
    if (token.elem.removeEventListener) {
        token.elem.removeEventListener(token.event, token.handler);
    } else {
        token.elem.detachEvent("on" + token.event, token.handler);
    }
}

If you want a simpler version without the propagation and default prevention options but with this and event normalization, that would be this:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}
Diego Jancic
  • 7,280
  • 7
  • 52
  • 80
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • sorry,i cann't understand your code function listenHandler(e) { var ret = fn.apply(this, arguments); if (ret === false) { e.stopPropagation(); e.preventDefault(); } return(ret); } – Mohamed Mahmoud Zaki Apr 14 '12 at 00:56
  • 1
    @MohamedMahmoudZaki - This event handling abstraction adds a feature that if the event handler function returns `false`, then it will stop propagation and default handling of the event. If the event handler doesn't return false or doesn't return anything, then it skips that behavior. Because propagation and default behavior is different in older IE, it is useful to have an abstraction for this too. – jfriend00 Apr 14 '12 at 01:02
  • @MohamedMahmoudZaki - I already provided you with a couple errors in your code. Also, please don't put multi-line code in comments. It is completely unreadable. If you need to communicate multi-line code, then use the `edit` link and add it to your question, then add a comment referring to the code you've added. If your new to javascript, why wouldn't you just take one of my two event handling functions that already work? – jfriend00 Apr 14 '12 at 01:47
  • it works great and i finally understand what are stopPropagation() and cancelBubble() really do ...thanks aloooooot...jfriend00 – Mohamed Mahmoud Zaki Apr 14 '12 at 17:44
  • @jfriend00 thanks for the code. How would you unsubscribe from event listening? – Aleksandr Makov Dec 30 '15 at 19:03
  • @AleksandrMakov - `.removeEventListener()` is the standard method or `.detachEvent()` is the old, proprietary Microsoft method. – jfriend00 Dec 30 '15 at 20:28
  • I do not think the remove listener methods will work. The reference to the callback function is replaced by the reference to the listener function so the remove will probably fail. I remember vaguely I stumbled across this issue in the past. – spc16670 Jun 01 '16 at 09:30