View Full Version : Javascript event handlers

09-14-2011, 04:28 PM
can someone please explain the code in this link. Just this small bit since i seen it in a few different places.
it starts off with if (!e) ...
please explain wth that means :confused::(
thank you so much

heres the link - http://www.w3schools.com/js/tryit.asp?filename=try_dom_event_srcelement

09-14-2011, 04:49 PM
In that case e is the parameter to the event handler whichElement(). But depending on the browser, it will not be handed over automatically. E.g. in Internet Explorer, it will not be there. In that case e will be undefined. So if(!e) means "if e is undefined" ... on Internet Explorer this condition will be met and e is assigned with the global event object instead.

09-15-2011, 02:59 AM
thanks. that helped. i see now.

if you dont mind, would you be able to explain each line of the code for me in basic pseudo code/rough english? :)

If you dont mind :)

Old Pedant
09-15-2011, 05:39 AM
// declare a function which takes one argument
// *if* the argument is passed to the function, the variable e will be non-null
function whichElement(e)
// declare a variable to be defined later
var targ;
// find out if [b]e[/e] has a value in it
// personally, I *DO NOT LIKE* seeing this coded the way it is
// because it doesn't make it clear what is really going on
// I would have coded it as
// if ( e == null )
if (!e) /* means the same thing as my code */
// if no argument was passed to the function,
// then assume that the browser is MSIE 8 and before
// and get the builtin global event from MSIE:
var e=window.event;
// find out if the object referenced by e has a property named target
// again, I think it would be clearer to write the next line as
// if ( e.target != null )
if (e.target)
// okay, so there is such a property...assign it to the targ variable
// if the variable doesn't have a target property,
// maybe it has a srcElement property
// and, again, it would be clearer to write it as
// if ( e.srcElement != null )
else if (e.srcElement)
// okay, so there is such a property...assign it to the targ variable
// as the comment says, the Safari browser has a bug
if (targ.nodeType==3) // defeat Safari bug
// so for it we really want to get the parent of the target that Safari found
targ = targ.parentNode;
// declare another variable
var tname;
// find out what kind of element (tag) we found as the target
// and give a message
alert("You clicked on a " + tname + " element.");

What's wrong with that code (other than my objections to its coding style)?

Well, suppose that the function is called with an argument that is *NOT* an object that has either a target or srcElement property? Then the varible targ will never get initialized and so when we get to the targ.tagName we get an error, because there is never any property on a null object.

So this function should *only* be called from the onclick of some tag.