JQuery: event.preventdefault does not work with Firefox (Mac and PC)

I have this jQuery bit that switches the paragraph after the H3 link. It works in IE and Chrome on PC and on Safari and Mac on Mac. In Firefox on both platforms, clicking a link does nothing?

<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 turn off event.preventDefault (); the section it works in Firefox, but of course I get a page that jumps at the top that I don't want. What can I do to make it work in Firefox?

+4
source share
2 answers

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

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

Comment from TJ Crowder regarding the inclusion of the evt () function

You need to declare the parameter to the click handler (the event is not global, except for IE and browsers that throw dice on IE-specific websites). Note that you do not need (or need) a test for preventDefault. jQuery ships it in browsers that don't provide it natively

Learn more about jQuery events.

+16
source

You need to specify 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 has already been answered fooobar.com/questions/1350807 / ...

Notice how the handler in the documents shows this eventObject as the parameter passed to it: http://api.jquery.com/click/

Note that the Event object has a preventDefault method: http://api.jquery.com/category/events/event-object/

+1
source

All Articles