Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIsten for a click on a link even if it's inside of a div or img

I use a click listener like this so that a click that goes to link.php will execute some code:

document.addEventListener('click', function(e) {    
    var tre = e.target.href || '';
    if( tre.indexOf("link.php") > -1) {
        alert('it worked');
    }
}, false);

This works:

<a href="/link.php?destination=1" target="_blank">
    link text
</a>

But clicks on images or divs don't:

<a href="/link.php?destination=1" target="_blank">
    <img src="/image.jpg">
    <span>link text</span>
</a>

since clicks are on the image and span, not the <a> tag. What's the simplest way to make this work?

like image 905
pg. Avatar asked Jan 07 '23 17:01

pg.


1 Answers

JavaScript does have a native .closest() method (although it is currently considered experimental and has limited browser support). You can use this method in order to get the closest a ancestor element (or the element itself, which means that it would work in both of the cases that you provided).

Example Here

document.addEventListener('click', function(e) {    
    var href = e.target.closest('a').href || '';
    if (href.indexOf("link.php") > -1) {
      // ...
    }
}, false);

Alternatively, you could check if each parent node is an a element:

Example Here

document.addEventListener('click', function(e) {
  var target = e.target

  while (target && target.tagName !== 'A') {
    target = target.parentNode;
    if (!target) { return; }
  }

  if (target.href.indexOf("link.php") > -1) {
    // ...
  }
}, false);

Another option is to attach the event listener directly to the a element and then access the currentTarget property in order to get the element that the event was attached to (rather than the element that triggered the event). However, that would only attach the event to a single a element:

Example Here

document.querySelector('a').addEventListener('click', function(e) {    
    var href = e.currentTarget.href || '';
    if (href.indexOf("link.php") > -1) {
      // ...
    }
}, false);
like image 146
Josh Crozier Avatar answered Jan 25 '23 19:01

Josh Crozier