Is there a way to achieve this in javascript. Below is the example of anchor tag
<a href="#">Example</a>
Is there a way to achieve this in javascript. Below is the example of anchor tag
<a href="#">Example</a>
With event delegation, you can attach an event listener to the body and preventDefault when any <a> is clicked which has that href.
document.body.addEventListener('click', (e) => {
const a = e.target.closest('a');
if (a.href === '#') {
e.preventDefault();
}
});
<a href="#">Example</a>
That'll prevent the # in the URL. If you want to make it truly unclickable, you can use pointer-events: none.
a[href="#"] {
pointer-events: none;
}
<a href="#">Example</a>
You can try setting the pointer-events property to none
a[href="#"]{
pointer-events: none;
}
<a href="#">Example</a>
<br>
<a href="">Clickable Link Example</a>
For any hash href, like #top
The solutions so far assume the href is exactly #. If you want to prevent clicks on any href starting with a hash, like #top, you could do that too.
The CSS approach, with a fancier attribute selector:
a[href^="#"] {
pointer-events: none;
}
The JS approach:
window.addEventListener('click', e => {
if (e.target.closest('a[href^="#"]')) {
e.preventDefault();
}
});