user31782
user31782

Reputation: 7589

Why don't event delegation work if I mention the outermost selector?

Suppose I make mouseover event delegated by mentioning the outermost selector in target name as:

$(".outer").on("mouseenter", ".outer .inner", function() {

  console.log("YES");

});
.outer {
  background: green;
  padding: 20px;
}
.inner {
  padding: 10px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <span class="inner">
    Hover
  <span>  
</div>  

In $(".outer").on("mouseenter", " .outer .inner",... If I do not mentioned .outer in .outer .inner then the code works as:

$(".outer").on("mouseenter", ".inner", function() {

  console.log("YES");

});
.outer {
  background: green;
  padding: 20px;
}
.inner {
  padding: 10px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <span class="inner">
    Hover
  <span>  
</div>  

Now as you can see in the console the mouseenter event works. But did it not work in first example? Donn't .outer .inner and .inner select the same DOM element?

Upvotes: 0

Views: 18

Answers (1)

Graham
Graham

Reputation: 6562

From the jQuery docs, the selector you pass in is:

A selector string to filter the descendants of the selected elements that trigger the event

So .outer .inner does not work, as no such element exists inside the .outer that triggers the event.

Upvotes: 1

Related Questions