Tuesday 20 June 2017

Javascript: What does 'return false;' do in event handler?

Bootstrap dropdown menu HTML

 <ul class="dropdown-menu">  
   <li><a href="#" id="edit">Edit</a></li>  
   <li><a href="#" id="delete">Delete</a></li>  
 </ul>  

jQuery code

 $("#delete").click(function (event) {  
   console.log("clicked");  
   return false;  
 });  

With 'return false;', double clicking the link prints out 'clicked' twice

 $("#delete").click(function (event) {  
   console.log("clicked");  
 });  

Without' return false;',  double clicking the link prints out 'clicked' once

Turns out what 'return false' does is event.preventDefault() and event.stopPropagation(). When the propagation is stopped, the bootstrap javascript code, which hides the dropdown menu, doesn't have a chance to be executed.

To see the difference, we can compare the effect when single clicking the link. Without 'return false;' the dropdown menu disappears. With return false; the dropdown menu still lingers.

The lesson is always use event.preventDefault() as opposed to return false; for event handing. The above code is best written as

 $("#delete").click(function (event) {  
   event.preventDefault();  
   console.log("clicked");  
 });