Sometimes, we want to prevent reload with link onclick without “#”.
In this article, we’ll look at how to prevent reload with link onclick without “#”.
How to prevent reload with link onclick without “#”?
To prevent reload with link onclick without “#”, we can call e.preventDefault
inside the click event handler.
For instance, we write:
<a href=''>click me</a>
to add a link.
Then we write:
const a = document.querySelector('a')
a.onclick = (e) => {
e.preventDefault()
console.log('clicked')
}
to select the link with querySelector
.
Next, we set a.onclick
to a function that calls e.preventDefault
to stop the default behavior, which is to refresh the page.
Therefore, when we click on the link, we see 'clicked'
logged.
Conclusion
To prevent reload with link onclick without “#”, we can call e.preventDefault
inside the click event handler.