2

Think before using “return false;”

One of the first things jQuery coders learn is how they can stop the browser from calling the default action of an event.

$('a').click(function(){
    alert('You have clicked the link!');
    return false; //stop browser from opening the link - DONT USE! SEE BELOW
})

“return false;” will stop the browser calling the default behaviour: opening the clicked link. But using “return false;” in that way is very bad.

What “return false” is really doing

“return false;” does not only stop the browser from calling the default behaviour, it also stops events from propagating so they can’t be handled somewhere else!

jQuery event.js Line 393+: Handle return false; :

if ( ret !== undefined ) {
    if ( (event.result = ret) === false ) {
        event.preventDefault();
        event.stopPropagation();
    }
}

The correct method

“stop the browser from calling the default action” – thats what we want to achieve. Like you can see in the above jQuery code, “return false;” calls preventDefault() and stopPropagation().

stopPropagation(): Stop events from propagate
preventDefault(): Stop default behaviour of browser

So in most cases, especially when working with jQuery Plugins you will only need to apply preventDefault to an event because the event must propagate.

$('a').click(function(e){
    alert('You have clicked the link!');
    e.preventDefault(); // correct method
    return true;
})

Michi

Passion for sports with boards, climbing, mountain biking, traveling, photography, videography and software engineering. /n/n Heilbronn // Germany

2 Comments

  1. Ein Rückgabewert wird nicht benötigt, ist aber evtl. sinnvoll wenn Du an einer anderen Stelle prüfen möchtest, ob die Funktion einen Fehler geschmissen hat.

Leave a Reply

Your email address will not be published. Required fields are marked *