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

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?

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


Need Your Help

Is it possible to have different layout elements inside CollapsingToolbarLayout?

android android-toolbar androiddesignsupport android-collapsingtoolbarlayout

I'm trying to place LinearLayout which contains imageview buttons and other UI elements inside the CollapsingToolbarLayout, is it possible?

Using ExpandoObject when property names are dynamic, is this possible?

c# dynamic expandoobject

I need to create an object that has properties that are named dynamically like: