Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault() always just before the end of the functions

Tags:

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?

like image 834
Olivier Pons Avatar asked Dec 02 '15 15:12

Olivier Pons


People also ask

What is the use of event preventDefault () method?

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.

What is the difference between event preventDefault () and return false?

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() .

What is event preventDefault () and event 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.


1 Answers

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) :)

like image 119
Gone Coding Avatar answered Sep 22 '22 04:09

Gone Coding