I have this in my code:
<div class="someClass">
<div id="22" class="otherClass" onclick="goToEdit();">Title</div>
<div class="parent">Other title</div>
</div>
And:
function goToEdit()
{
tree.selectItem($(event.target).attr('id'));
btnMyButton_onclick();
}
In Chrome everything works fine, but in Mozilla it doesn’t react to the click event. Why?
Doh! We should all have realized.
The thing is that
eventis not a global on most browsers, though it is on IE and Chrome throws a bone to sites designed for IE by making it global as well as doing what it should do (passing it into the event handler function).Your best bet by far is to not use
onclick="code"at all (see below), but you can also do this:…which should work cross-browser. It works because the
eventobject is defined in the special context in whichonclickhandlers are called (on browsers that do this in a standard way), or it’s a global (on IE), and so either way it’s defined at that point (but not necessarily, as a global, later in yourgoToEditfunction — which is why we pass it in as an argument).But again, I wouldn’t do that. Instead, I’d make the
idvalue valid for CSS by having it start with a letter, and use jQuery to hook up the handler:HTML:
JavaScript:
Notes:
doff the beginning of theidvalue before passing it on. I assume it was22for a reason.$(event.target).attr('id'), just useevent.target.iddirectly.If the
divmay contain other elements (spans,ems,ps, etc.), note thatevent.targetmay not be thediv, it may be a descendant element of thediv.thiswill always be thediv, though (jQuery sees to that), so: