Event.preventDefault () is always immediately before the completion of functions

In almost all of the sample scripts / templates I can find, I see event.preventDefault(); at the end of a function, for example:

 $('.navbar-nav li a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); 

From my point of view, the idea is that "immediately stop the default behavior and then do everything we have to do," for example:

 $('.navbar-nav li a').bind('click', function(event) { event.preventDefault(); var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); }); 

So what am I missing?

+8
jquery preventdefault
source share
1 answer

This does not matter in the two specified specific examples. Put it where you like :)

The usual reason for having it at the end is when it replaces return false; , as usual, when there should have been a return. return false is a shortcut for e.preventDefault() and e.stopPropagation() .

Another thing to keep in mind is when you need to conditionally stop it, in which case preventDefault() goes in the middle ( if , etc.) :)

+11
source share

All Articles