0

How do I make the code below not catch the elements <a> with the attribute target="blank"? Because location.href = link.href; opens in the same card (only links with target="blank" should open in a new card without animation).

document.addEventListener('click', function(event) {
if (event.target.tagName !== "A" || !event.target.href) return;
event.preventDefault();
var link = event.target;
document.body.style.opacity = 0;
document.body.addEventListener("transitionend", function() {
location.href = link.href;
});
});

If more clarification is needed, please comment below!

Ali Heikal
  • 3,790
  • 3
  • 18
  • 24
Majonez.exe
  • 412
  • 8
  • 22

2 Answers2

1

Just use the below if condition:

event.target.getAttribute('target') !== blank);

Hope it works.

Rastalamm
  • 1,712
  • 3
  • 23
  • 32
1

Check event.target.target.

document.addEventListener('click', function(event) {
  if (event.target.tagName !== "A" || !event.target.href || event.target.target == "_blank") return;
  event.preventDefault();
  var link = event.target;
  document.body.style.opacity = 0;
  document.body.addEventListener("transitionend", function() {
    location.href = link.href;
  });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Do you have any idea that the request should be sent by the XHR and that the URL of the site should also change? – Majonez.exe Jan 10 '20 at 20:24
  • I think you can use the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL. – Barmar Jan 10 '20 at 20:28
  • I think to use just the XHR request to send it to the server and how will it return to display this return on the page then change the URL in the browser (I have something like this but the code obviously doesn't work...), I don't know how to make JS scripts work in the obtained code – Majonez.exe Jan 10 '20 at 20:33
  • That's difficult. jQuery does it by parsing the returned HTML, looking for ` – Barmar Jan 10 '20 at 20:37
  • I hate Jquery, maybe the code is easier to write but I don't prefer to use any libraries. – Majonez.exe Jan 10 '20 at 20:37
  • I wasn't saying you should use jQuery, just telling you how it gets around this problem. – Barmar Jan 10 '20 at 20:42
  • You know how to write a code this way? I don't think it's that long, the one I have for this moment has about 10 lines (it doesn't interpret JS and doesn't change the URL. – Majonez.exe Jan 10 '20 at 20:44
  • Read the question I linked to, it has some code examples. – Barmar Jan 10 '20 at 20:46
  • https://stackoverflow.com/a/16278226/11860129 but this is interesing. – Majonez.exe Jan 10 '20 at 20:49