Search This Blog

Wednesday, February 17, 2016

Difference between ‘return false;’ and ‘e.preventDefault();’

Step1:


Have you ever seen those two things (in the title) being used in jQuery? Here is a simple example:

$("a").click(function() {
   $("body").append($(this).attr("href"));
   return false;
}

Step2:

That code would append the href attribute as text to the body every time a link was clicked but not actually go to that link. The return false; part of that code prevents the browser from performing the default action for that link. That exact thing could be written like this:

$("a").click(function(e) {
   $("body").append($(this).attr("href"));
   e.preventDefault();
}
 

So what's the difference?

The difference is that return false; takes things a bit further in that it also prevents that event from propagating (or "bubbling up") the DOM. The you-may-not-know-this bit is that whenever an event happens on an element, that event is triggered on every single parent element as well. So let's say you have a box inside a box. Both boxes have click events on them. Click on the inner box, a click will trigger on the outer box too, unless you prevent propagation. Like this:



 e.preventDefault();
 
click(function(e) - E is Event
 
  

Step3:

e.preventDefault();- Event prevent Default 

 
when you specify  function(e) - it trigger only the current event of the function.
 
and stop current event function.
 

return false - Stop all the events including parent child everything in function

 
when you specify  return False - it trigger entire event to stop.
 

Step4:

 


Enjoy Folks

No comments:

Post a Comment

Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...