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) {
        event.preventDefault();
        /* 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="https://developer.mozilla.org/">MDN</a>

<script>
var link = document.querySelector("a");
link.addEventListener("click", function(event) {
    console.log("Nope.");
    event.preventDefault();
});
</script>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +