Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript event handling, why "return false" or "event.preventDefault()" and "stopping the event flow" will make a difference?

It is said that when we handle a "click event", returning false or calling event.preventDefault() makes a difference, in which

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.

Does that mean, if the click event is registered several times for several actions, using

$('#clickme').click(function() { … })

returning false will stop the other handlers from running?

I am on a Mac now and so can only use Firefox and Chrome but not IE, which has a different event model, and tested it on Firefox and Chrome by adding 3 handlers, and all 3 handlers ran without any stopping…. so what is the real difference, or, is there a situation where "stopping the event flow" is not desirable?

This is related to

Using jQuery's animate(), if the clicked on element is "<a href="#" ...> </a>", the function should still return false?

and

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

like image 495
nonopolarity Avatar asked Jun 15 '10 02:06

nonopolarity


2 Answers

hopes this code can explain it to you...

html

<div>
<a href="index.html" class="a1">click me</a>
<a href="index.html" class="a2">click me</a>
</div>​

jquery

$('div').click(function(){
    alert('I am from <div>');
});

$('a.a1').click(function(){
    alert('I am from <a>');
    return false; // this will produce one alert
});

$('a.a2').click(function(e){
    alert('I am from <a>');
    e.preventDefault(); // this will produce two alerts
});​

demo

or

$('div').click(function(){
    alert('I am from <div>');
});

$('a').click(function(){
    alert('I am from <a>');
});

$('a.a1').click(function(){
    alert('I am from <a class="a1">');
    return false;
});

$('a.a2').click(function(e){
    alert('I am from <a class="a2">');
    e.preventDefault();
});​

demo 2

like image 114
Reigel Avatar answered Sep 29 '22 16:09

Reigel


Writing return false or e.preventDefault() will not prevent other handlers from running.

Rather, they will prevent the browser's default reaction, such as navigating to a link.

In jQuery, you can write e.stopImmediatePropagation() to prevent other handlers from running.

like image 44
SLaks Avatar answered Sep 29 '22 15:09

SLaks