Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check if target is link

I have a global function to capture clicks.

$(document).click(function(e){
  //do something
  if(clickedOnLink)
    //do something
});

I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.

http://jsfiddle.net/Af37v/

like image 887
XCS Avatar asked Jan 14 '13 21:01

XCS


2 Answers

I believe using is will actually have better performance than the answers suggesting closest:

$(e.target).is('a, a *');

This checks if the element itself is an a or if it is contained with an a.

This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.

like image 141
James Montagne Avatar answered Oct 04 '22 02:10

James Montagne


If the exact target is link, then you can use .is()

Example:

$(".element").on("click", function(e){
  if($(e.target).is("a")){
    //do your stuff
  }
});

EDIT:

If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length

Example:

$(".element").on("click", function(e){
  if($(e.target).closest("a").length){
    //do your stuff
  }
});
like image 37
Ari Avatar answered Oct 04 '22 02:10

Ari