Think before using 'return false;'

Posted on 27. September 2013

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 not good because this can break everything behind.

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" – that is 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; })
Made with ♥️ and Gatsby © 2022