Canceling default action in JavaScript
Sometimes you need to use JavaScript to cancel the default action of a tag. For example, by clicking on a link, cancel the transition to this link. As a rule, this is required if we use this link just to run some code. In this case, the fact that when you click on the link will follow it, we do not need at all.
The default action is canceled using the Event
object. To do this, it has a special method
preventDefault()
, which should be called
anywhere in the event handler.
Let's try it in practice. Let's have a link like this:
<a href="/" id="elem">link</a>
Let's make it so that clicking on the link does not lead to another page:
let elem = document.querySelector('#elem');
elem.addEventListener('click', function(event) {
event.preventDefault();
console.log('You cannot follow this link!');
});
Links are given. Make it so that when you click on the link, its href is written to the its end, and there is no transition by link.
Given two inputs, a paragraph and a link. Let numbers be entered into the inputs. Make it so that when you click on the link, the sum of the entered numbers is written to the paragraph.