Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 549
Andy Nightingale Avatar asked Dec 03 '22 08:12

Andy Nightingale


1 Answers

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

like image 124
Nicky Waites Avatar answered Jan 17 '23 13:01

Nicky Waites