19.10 Suppressing the Default Action of Events
HTML elements such as a simple link or a button to submit a form perform the intended actions when events occur, even without JavaScript. For example, clicking on a link triggers a click event, which usually causes the web browser to load a new web page. Clicking a Submit button on a form also triggers a submit event, which submits the form to the web server.
Certain events, as just mentioned, are handled by the web browser in such a way that it executes a default action without the need to set up a special event handler function in JavaScript.
Here’s a simple example that demonstrates this:
<a class="aLink" href="https://www.rheinwerk-computing.com/">A link</a>
Now, if you want to take control of JavaScript yourself and, instead of following the link and loading a new web page, do something else, you need to suppress the default action of the element. For this purpose, you can use the preventDefault()method of the event object:
event.preventDefault();
You can use this method to suppress the intended default action. This process is also referred to as an event cancellation.
Here’s a complete example that demonstrates how you can suppress the default action of the click event for a link. In the example, only the default action of following the link and loading the website is suppressed, and a message gets displayed instead in the console indicating that the default action has been suppressed:
...
document.querySelector('.aLink').onclick = function(event) {
if (event.preventDefault) {
event.preventDefault();
}
// Write the actual JavaScript code here, which states
// what is supposed to happen when the link gets clicked on
console.log("Default action prevented");
}
...
Listing 19.34 /examples/chapter019/19_10/js/script.js