Andy Nightingale
Andy Nightingale

Reputation: 149

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?

Upvotes: 4

Views: 10203

Answers (2)

Hitesh
Hitesh

Reputation: 4288

You need to provide the Event parameter:

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

This question already been answered here https://stackoverflow.com/a/17712808

Note how the handler in the docs show this eventObject as the parameter passed to it: http://api.jquery.com/click/

And note how the Event object has the preventDefault method: http://api.jquery.com/category/events/event-object/

Upvotes: 1

Nicky Waites
Nicky Waites

Reputation: 2428

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

Upvotes: 16

Related Questions