Prevent `<a>` tags from redirecting

59 Views Asked by At

I am trying to create a single-page application with a music player. That's why I want to prevent <a> tags from redirecting, which in turn causes the player to stop. I tried several approaches such as:

document.addEventListener('click', event => {
    if (event.target.tagName === 'A') {
        event.preventDefault();
        navigate(event.target.href);
    }
});

or

document.addEventListener('DOMContentLoaded', () => {
    const links = document.querySelectorAll('a');
    links.forEach(link => {
        link.addEventListener('click', event => {
            event.preventDefault();
            navigate(event.target.href);
        });
    });
});

or

<body onload="preventRedirect()">...</body>
function preventRedirect(){
    const links = document.querySelectorAll("a");
    links.forEach(link => {
        link.addEventListener("click", event => {
            event.preventDefault();
            navigate(link.href);
        })
    })
}

Neither of these worked. The strange thing is, however, that if I execute the function or add the event listeners inside the console manually, everything finally works as expected. I know that I should be using buttons, but that would break the aesthetics of my design. I have tried setting the hrefs to "#" and using onclick to navigate, which works, but is tedious and I hope that my original idea will be able to work in the end.

1

There are 1 best solutions below

6
KooiInc On BEST ANSWER

Try using event delegation to create a handler on the document level. It resembles your first code piece. Maybe the use of navigate (an experimental technology) is the culprit of that not working. It will throw an error, because you can't use it like that (it should be [window].navigation.navigate(...), but using that it would follow the link).

document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.closest(`a`) /* && possible other conditions */) {
    console.clear();
    console.log(`will not follow ${evt.target.href}`);
    evt.preventDefault();
    /* possibly more code */
    return false;
  }
}
<p><a href="https://www.google.com">(non clickable) link to Google</a></p>
<p><a href="https://www.microsoft.com">(non clickable) link to Microsoft</a></p>