user2199267
user2199267

Reputation:

$(e.target) equals a link even if clicking on element within?

I feel I should be more experienced then this however I just cannot seem to resolve. Upon clicking on the link or anything within, I want this to be the $(e.target) to call the parent or whatnot.

A breakdown of my script looks like the following;

$(document).on('mousedown', function(e) {
    if ($(e.target).is('ul.SiteNav>li>a')) {
    alert('Hello World!')
  }
});

Of course this is just a snippet but nevertheless, I'm new to using $(e.target) an despite my searches, I cannot resolve to as why you cannot click the <i></i> within the <a></a> because you're still clicking on the link, aren't you/...

Here is a JSFiddle example of my problem

Upvotes: 0

Views: 99

Answers (2)

GolezTrol
GolezTrol

Reputation: 116140

You can click it, and you actually get the event. Only e.target is the element you clicked. And it makes sense. The handlers is on document, the element is the i.. why would the link get the click?

You can try to find it in the parent chain using closest(). It will give a result when the element itself or one of its parents match the given selector.

$(document).on('mousedown', function(e) {
  if ($(e.target).closest('ul.SiteNav>li>a').length > 0) {
    alert('Hello World!')
  }
});
.SiteNav {
  List-style:none;
}
a {
	float:left;
	height:42px;
	line-height:42px;
	padding:0 10px;
	color: #f7dd71;
	text-decoration: none;
	font-size: 14px;
	font-family: "Comic Sans MS", cursive, sans-serif;
	font-weight: bold;
}
a:nth-of-type(1) { padding-right:2px; }
a:nth-of-type(2) { padding:0 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="SiteNav">
  <li><a href="javascript:;" data-link="Reply">Reply</a></li>
  <li><a href="javascript:;" data-link="Reply"><i class="fa fa-angle-down"></i></a></li>
</ul>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

target will be whatever deepest level element you actually interact with but what is likely confusing you is that events bubble up the dom tree so if an event handler was listening to <a> click, clicking on a child will still bubble to the parent and trigger the event handler

Use closest() to do what you want

if ($(e.target).closest('.SiteNav a').length){
   // code if <a> expected
}else{
   // do something else when not <a>
 }

closest() will also include the actual target and work it's way up from that start point.

Upvotes: 1

Related Questions