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!
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!
Some elements trigger actions by default. For example:
href.action attribute.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
})
Prevent the default behavior of the following elements:
href that points to google.comWatch what happens when you trigger the event after doing so. (Hint: nothing should happen).
<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()
})