Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:

1. event.preventDefault()

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

// custom handling here

e.preventDefault(); 

});

2. return false

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

// custom handling here 

return false; 

});

Is there any significant difference between those two methods of stopping event propagation?

For me, return false; is simpler, shorter and probably less error-prone than executing a method. With the method, you have to remember about correct casing, parentheses, etc.

Also, I have to define the first parameter in the callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?

1 Answer

0 votes
by (106k points)
edited by

The return false statement within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.

The method e.preventDefault() will prevent the default event from occurring where as the method e.stopPropagation() will prevent the event from bubbling up and return false.

Check out this Web Development course to enhance your career!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Mar 25, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...