Preventing Default Behavior

Html elements have default action associated with them. For example if you click a link, you will be taken to the link's target. If you press the down arrow, the browser will scroll the page down. If you right-click, you'll get a context menu. Using JavaScript event handlers you can prevent the default behavior attached with these DOM elements.

The JavaScript event handlers are called before the default behavior is performed. It can call the preventDefault method on the event object.

For example, a link with an href value wants to go to another page, or in our case, a form that wants to submit somewhere to do a search query.

Preventing default behavior is done inside the method. You first need to pass the event (form submit) as an argument into the method. Then attach the preventDefault() method to it.

var adr = {
    search: function(event) {
        /* continue the rest of the method here */

Another example it is used to implement your own keyboard shortcuts or context menu.

It can also be used to obnoxiously interfere with the behavior that users expect. For example, here is a link that cannot be followed.

<a href="">MDN</a>

var link = document.querySelector("a");
link.addEventListener("click", function(event) {
Related Tutorial
Follow Us #
Contents +