Home > Software design >  Why doesn't the click on the anchor tag first visit the link?
Why doesn't the click on the anchor tag first visit the link?

Time:07-08

For the following code:

links.addEventListener("click", e => {
  const a = e.target.closest("a");
  if (!a) return;

  const confirmation = confirm(`Go to ${a.href}?`);

  if (!confirmation) e.preventDefault();
});
<div id="links">
  <p>Lorem ipsum dolor sit <a href="https://wikipedia.org">Wikipedia</a> consectetur adipisicing elit. Molestias temporibus <a href="https://developer.mozilla.org/en-US/"><i>Mozilla Developer Network (MDN)</i></a> labore eveniet dolor sunt soluta voluptate
    quas. Reprehenderit, quam voluptatem.</p>
</div>

Why doesn't a click on the a tag first visit the link but just opens the confirm which is defined in my javascript file?

CodePudding user response:

You need to modify your JS code, first prevent the default behaviour of the link then ask for confirmation, if the result is true, you can use window.location ,There is a similar question which can give you more info: Adding click event via addEventListener to confirm navigation from a hyperlink

CodePudding user response:

The reason your a tag does not go to the href is because the eventListener gets priority. Try this code instead:

links.addEventListener("click", e => {
  const a = e.target.closest("a");
  a.preventDefault()
  if (!a) return;

  const confirmation = confirm(`Go to ${a.href}?`);

  if (confirmation){ 
    window.location.assign(a.href); 
  }
});
  • Related