Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between e.preventDefault(); and return false? [duplicate]

Tags:

jquery

$("a.avatar").click(function(e){       e.preventDefault();       $("#thumbnails").fadeIn();     }); 

and

$("a.avatar").click(function(e){       $("#thumbnails").fadeIn();           return false;     }); 

Both can achieve the same goal for me.

like image 952
user198729 Avatar asked Jan 07 '10 02:01

user198729


People also ask

What is the difference between event preventDefault () and return false?

preventDefault() prevents the default browser behavior for a given element. stopPropagation() stops an event from bubbling or propagating up the DOM tree. Whereas, return false is a combination of both preventDefault() and stopPropagation() .

Is there any significant difference between event preventDefault () vs return false to stop event propagation?

e. preventDefault() will prevent the default event from occuring, e. stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.

What does the e preventDefault () function do?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What is the opposite of event preventDefault ()?

There is no opposite method of event. preventDefault() to understand why you first have to look into what event. preventDefault() does when you call it. Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution.


1 Answers

Returning false from jQuery event handlers is equivalent to calling both, e.preventDefault and e.stopPropagation.

So the difference is that preventDefault will only prevent the default event action to occur, i.e. a page redirect on a link click, a form submission, etc. and return false will also stop the event flow.

like image 172
Christian C. Salvadó Avatar answered Sep 28 '22 16:09

Christian C. Salvadó