event.preventDefault() vs. return false is a very important but confusing topic that which one should be used and for what. When we want to prevent other event handlers from executing after a certain event is fired, we can use one of these two techniques.
1. event.preventDefault()
2. return false
1. event.preventDefault() :
1 2 3 4 | $('a').click(function (e) { // custom handling here e.preventDefault(); }); |
2. return false :
1 2 3 4 | $('a').click(function () { // process here return false; }); |
event.preventDefault() will prevent the default event from occuring like return false but has some difference and sometimes it will create confusion which will be the best to use and why.
Suppose we are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If our click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag’s default behavior.
1 2 3 4 5 6 7 | $('a.link').click(function (e) { // process here // oops...runtime error...where will the href take me? return false; }); |
But over this, if we add event.preventDefault() as the first line in the handler, will guarantee that the anchor’s default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).
1 2 3 4 5 | $('a').click(function (e) { e.preventDefault(); // process here // oops...runtime error, but at least the user isn't navigated away. }); |
Suppose if we can place a lot of functions on the onClick event for one element. How can we be sure the false one will be the last one to fire?
preventDefault on the other hand will definitely prevent only the default behavior of the element.
So it depends on the situation, if we don’t have any chance of occurring any error/exception in our code we can use any of them but have chance of error/exception, than better to use event.preventDefault() at the first line in the event handler.