I always define the function before using it, though that may or may not be important. And, I include the little e to pass the event for browsers that do it that way (basically all but IE):
Code:
function eventHandler(e)
{
alert("Hello") ;
}
if ( typeof window.addEventListener != "undefined" )
myObject.addEventListener( "click", eventHandler, false );
else if ( typeof window.attachEvent != "undefined" )
myObject.attachEvent( "onclick", eventHandler );
Now, there may be a way to pass other arguments but, I don't think so. Think of it, the function is being added. So, how would you know what the other arguments would be? You can pass information as properties of the event:
Code:
function eventHandler(e)
{
var e=e? e : window.event;
var el=e.target? e.target : e.srcElement;
alert(el.tagName) ;
}
In the above we've grabbed the target (all but IE) or source element (IE) of the event and are alerting its tag name.
Once you have the element in question, you can find all sorts of things if it has them, like its parentNode, its id or class name, whatever. Just make sure it is going to have those things or test if they exist before grabbing them. Like, with id:
Code:
if(el.id)
alert(el.id)
You could also pass variables to the function by defining them in some scope that includes the function and then referring to them within the function, but that is a little hard to show in any meaningful way without greater context.
A simple example would be:
Code:
var bob='sam';
function eventHandler()
{
alert(bob) ;
}
which would alert the name 'sam'.
Bookmarks