user1322207 user1322207 - 1 month ago 6x
jQuery Question

Div onclick event not called in Mozilla

I have this in my code:

<div class="someClass">
<div id="22" class="otherClass" onclick="goToEdit();">Title</div>
<div class="parent">Other title</div>


function goToEdit()

In Chrome everything works fine, but in Mozilla it doesn't react to the click event. Why?


I get error that event is not defined

Doh! We should all have realized.

The thing is that event is 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:

<div id="22" class="otherClass" onclick="goToEdit(event);">Title</div>

...which should work cross-browser. It works because the event object is defined in the special context in which onclick handlers 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 your goToEdit function — which is why we pass it in as an argument).

But again, I wouldn't do that. Instead, I'd make the id value valid for CSS by having it start with a letter, and use jQuery to hook up the handler:


<div id="d22" class="otherClass">Title</div>


function goToEdit(event) {


  • I striped the d off the beginning of the id value before passing it on. I assume it was 22 for a reason.
  • There's no reason to do $('id'), just use directly.
  • If the div may contain other elements (spans, ems, ps, etc.), note that may not be the div, it may be a descendant element of the div. this will always be the div, though (jQuery sees to that), so:

    function goToEdit(event) {