Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent `<a>` tags from redirecting

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading