Tutorials JavaScript JavaScript Event Bubbling and Return False

JavaScript Event Bubbling and Return False

Hello everybody and welcome back to PHP Trainee. Today's tutorial is about JavaScript's event triggers with Return False.

$('a').click(function() {
  // Do stuff on click
  
  // Prevent browser from going to actual link
  return false;
});

I'm sure you've seen the return false statement a lot when you do JavaScript. It's very common on anchor clicks where you want to use JavaScript to handle the event instead of the browser going to a new page. This works pretty well if you want a big red "shutdown" button. However, it becomes problematic when you only want one part to turn off.

What does Return False do?

  • event.preventDefault
  • event.stopPropagation (jQuery Only)
  • Halts the current function immediately

event.preventDefault

90% of the time, you only need preventDefault. This prevents the default action of the browser, which is usually to send you to another page.

$('a').click(function(e) {
  // Do stuff on click
  
  // Prevent browser from going to actual link
  e.preventDefault();
});

event.stopPropagation

Normally, parent events trigger on children too. If you have an anchor inside a div, and you put a function on that div, the anchor inherits that function. stopPropagation stops the children from inheriting functions from their parents.

<div>I am a div. <a href="#">I am an anchor.</a></div>
$('div').click(function(e) {
  alert('div click');
});
$('a').click(function(e) {
  // Do stuff on click
  
  // I am not a div! Stop alerting!
  e.stopPropagation();
});

event.stopImmediatePropagation vs return false

The difference between stopImmediatePropagation and return false is that return false just kills the current function while stopImmediatePropagation finishes the current function but kills future functions on the element with the same event.

$('a').click(function(e) {

  // This triggers
  win_chicken_pie_function();
  
  // You shall not pass!
  e.stopImmediatePropagation();

  // This still triggers after stopImmediatePropagation
  // because it is still in the original function
  win_one_million_dollars_function();
  
});
$('a').click(function(e) {

  // This never triggers after the above stopImmediatePropagation
  // because it is in a new click function
  freak_accident_gives_superman_powers_function();
  
});
$('a').click(function(e) {

  // This triggers
  win_chicken_pie_function();
  
  // You shall not pass!
  return false;

  // Return false kills the immediate function
  // and this function is never fired.
  win_one_million_dollars_function();
  
});
$('a').click(function(e) {

  // This event fires because it is a new click function 
  freak_accident_gives_superman_powers_function();
  
});

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.