Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make every anchor tag with hash (#) in href unclickabe

Tags:

javascript

css

Is there a way to achieve this in javascript. Below is the example of anchor tag

<a href="#">Example</a>
like image 391
Rishabh Avatar asked Dec 05 '25 04:12

Rishabh


1 Answers

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>
like image 101
CertainPerformance Avatar answered Dec 07 '25 19:12

CertainPerformance