Java Reference
In-Depth Information
Stopping Default Behavior
Some elements have default behavior associated with certain events. For example, when a
user clicks on a link, the browser redirects to the site in the href attribute, while a form is
submitted when the user clicks on the submit button.
preventDefault() is a method of the event object that can be used inside the call-
back function to stop the default behavior occurring. To see an example, add the following
line to the events.htm file:
<p>
<a id="broken" href="http://sitepoint.com">Broken Link</a>
</p>
Then add the following event listener inside the script.js file:
var broken = document.getElementById("broken");
broken.addEventListener("click",function(event) {
event.preventDefault();
console.log("Broken Link!");
});
This will stop the page from redirecting to the page specified in the href attribute and show
the message in the console instead.
Warning: Use preventDefault() with Caution
Make sure that you think carefully before using preventDefault() to
change default behavior. Users will expect certain behaviors and preventing
them may cause confusion.
Some events do not allow the default behavior to be prevented. This can vary
from browser to browser, but each event object has a property called can-
cellable that returns false if it cannot be prevented.
Search WWH ::




Custom Search