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…
In your function, I see you are using both
elemenetandelementwhere they should be the same spelling. That would be at least part of the problem.I also see that your
addEventsfunction 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
thispointer and theeventsobject so they can be treated the same in any browser too.If you want a simpler version without the propagation and default prevention options but with
thisandeventnormalization, that would be this: