preventDefault() – Cancel the browser’s action
Once browser fired or execute any event like onclick, onmouseover event, we can cancel or terminate or stop the execution of that event.
preventDefault() does not terminate or cancel the execution of the event. It will continue to execute the event function.
preventDefault() just keep the browser to it’s default behaviour.
HTML:
<a href="http://www.google.com" id="link">Click here to go google.com</a>
JS:
var btnSubmit = document.getElementById("link"); btnSubmit.onclick = function (event) { var event = event || window.event; event.preventDefault(); }
Stop link navigation live demo
We can also use the return false;
statement to cancel the execution of the event or keep the browser to it’s default behaviour.
Example 1:
HTML:
<a href="http://www.google.com" id="link">Click here to go google.com</a>
JS:
var btnSubmit = document.getElementById("link"); btnSubmit.onclick = function (event) { var event = event || window.event; return false; }
Example 2:
HTML:
<a href="http://www.google.com" onclick="return false;">Click here to go google.com</a>
Stop the submission of the form.
HTML:
<form onsubmit="return false;"> <input type="text" placeholder="First Name" /> <input type="text" placeholder="Last Name" /> <input type="submit" value="Click me" /> </form>
In above example, The form will be never submit to the server because we return false
from the onclick event of the form.
Stop the submission of the form live demo
preventDefault() Internet Explorer
All the latest and modern Internet Explorer browser supports the preventDefault() method but Internet Explorer< 9 does not supports the preventDefault().
So in IE < 9 we can use the return false; statment or we can also use the event.returnValue property to keep the browser to it’s default behaviour.
We have to set the event.returnValue property to false.
element.onclick = function (event) { var event = event || window.event; event.returnValue = false; }