10.4 Cancelling Default Actions
Finally, let’s talk about default actions. Many events in Javascript automatically lead to default browser actions. An example is when we click on a link on our webpage. This click should lead us to another web page specified by the href attribute.
If we want to prevent this default action from happening, we can cancel it using the built-in preventDefault() method.
Add the following code to EventsPractice.html (after the <body> tag):
<a id = "amazon" href = "http://www.amazon.com">Click Here to Go Amazon.com</a>
Next, add the following code to chap10.js.
function amazonLink(e) { alert("You shall not go"); } document.getElementById("amazon").addEventListener('click', amazonLink);
Save chap10.js and refresh EventsPractice.html. Click on the link. What happens? You see a pop-up message but are eventually directed to Amazon’s website right?
Now add the following line to the amazonLink() function:
e.preventDefault();
Run the code again. What happens now? You'll get the same pop-up message. However, this time, you'll not be directed to Amazon’s website. This is because the preventDefault() method has prevented that from happening.
Pretty cool right?
However, note that this method is not supported by IE 8 and below. In addition, not all default actions can be prevented. To check if a default action can be canceled, use the cancelable property.
Try adding the line
alert(e.cancelable);
to the amazonLink() function and run the program again. You’ll get an additional pop-up window that says "true". This indicates that the default action for this particular event can be canceled. If the default action cannot be canceled, you’ll get "false".