0 votes
1 view
in Web Technology by (47.8k 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 (107k points)

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.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...