Some elements trigger actions by default. For example:
- When you click on a link, browsers will navigate to the address indicated with
href. - When you click on a checkbox, browsers check or uncheck the checkbox.
- When you click on a submit button on a form, browsers trigger the submit event and redirect you to the page indicated by the
actionattribute.
Preventing default actions
Sometimes, you want to prevent these default behaviors. You’ll see why and when you’d do so as we build components. For now, learn how to prevent it.
To prevent default behaviors, you can use the preventDefault method.
Element.addEventListener('click', evt => evt.preventDefault())When the default action is prevented, browsers automatically set the defaultPrevented property to true.
Element.addEventListener('click', evt => { evt.preventDefault() console.log(evt.defaultPrevented) // true})Exercise
Prevent the default behavior of the following elements:
- A link with a
hrefthat points togoogle.com - A checkbox
Watch what happens when you trigger the event after doing so. (Hint: nothing should happen).
Prevent the default behavior a link with href that points to google.com:
<a href="https://google.com">Prevent link from opening google.com!</a>const link = document.querySelector('a')link.addEventListener('click', ev => { ev.preventDefault()})Prevent the default behavior of a checkbox:
<input type="checkbox" />const checkbox = document.querySelector('input')checkbox.addEventListener('click', ev => { ev.preventDefault()})Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson