In almost all the examples / templates scripts I can find, I see event.preventDefault();
at the end of the function, like this:
$('.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 "stop immediately the default behavior then do whatever we have to do", like this:
$('.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?
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .
The event. preventDefault() prevents the browsers default behaviour, but does not stop the event from bubbling up the DOM. The event. stopPropagation() prevents the event from bubbling up the DOM, but does not stop the browsers default behaviour.
It makes no difference in the two specific examples shown. Put it where you like :)
The usual reason for having it at the end is when it replaces return false;
as that was usually where the return had to be. return false
is a shortcut for both e.preventDefault()
and e.stopPropagation()
.
The other thing to bear in mind is when you need to conditionally stop it, in which case the preventDefault()
goes in the middle (of an if
etc) :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With