jQuery: event.preventdefault not working with Firefox (mac and PC)

Andy Nightingale picture Andy Nightingale · May 3, 2011 · Viewed 10k times · Source

I have this bit of jQuery toggling a paragraph after an H3 link. It works in IE and Chrome on PC and Safari and Chrome on Mac. On Firefox on both platforms, clicking the link does nothing at all?

<script type="text/javascript">
$(document).ready(function(){
$("#rightcolumn .article .collapse").hide();
$("#rightcolumn h3 a").click(function(){
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false; 
};
$(this).parent().next().toggle(400);
});
});
</script> 

If I disable the event.preventDefault(); section it works in Firefox, but of course then I get the page jumping to the top which I don't want. What can I do to get it working in Firefox?

Answer

Nicky Waites picture Nicky Waites · May 3, 2011

You are missing the event declaration from your function. Also as a convention I see most examples using evt as the variable name.

$("#rightcolumn h3 a").click(function(evt)
{
   evt.preventDefault();
   $(this).parent().next().toggle(400);
}

Comment from T.J. Crowder as to including the evt in function()

You need to declare the parameter to the click handler (event is not a global except on IE and browsers that throw a bone to IE-specific websites.) And note that you don't need (or want) the test for preventDefault. jQuery supplies it on browsers that don't provide it natively

More explanation on jQuery events