I'm having an issue with this piece of JavaScript. The issue is that when it is enabled, some of my links aren't working. The links that open a webpage work fine, it's the mailto: and tel: links that won't work. Can someone please help me fix this issue? Thank you.
const allLinks = document.querySelectorAll("a:link");
allLinks.forEach(function (link) {
link.addEventListener("click", function (e) {
// conditional for preventDefault
if (link.hasAttribute("target") === false) {
e.preventDefault();
} else {
if (link.getAttribute("target") !== "_blank") {
e.preventDefault();
}
}
const href = link.getAttribute("href");
// Scroll back to top
if (href === "#")
window.scrollTo({
top: 0,
behavior: "smooth",
});
Your code is preventing the link from being followed if it doesn't have a target attribute set to "_blank".
Tel and mailto links don't usually have a target. As @The Fool mentioned, this looks suspicious and it's unclear how you expected it to work.
You can probably fix it by adding the following to the top of your handler.
if (link.href.startsWith("tel:") || link.href.startsWith("mailto:")) {
return
}