Default Behaviors

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Default Behaviors

Some elements trigger actions by default. For example:

  1. When you click on a link, browsers will navigate to the address indicated with href.
  2. When you click on a checkbox, browsers check or uncheck the checkbox.
  3. When you click on a submit button on a form, browsers trigger the submit event and redirect you to the page indicated by the action attribute.

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:

  1. A link with a href that points to google.com
  2. A checkbox

Watch what happens when you trigger the event after doing so. (Hint: nothing should happen).

Answers

<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()
})