Yogo. Sh Yogo. Sh - 3 years ago 49
jQuery Question

JQuery each and on methods not working

The goal is simple. When hover over mydiv (gray) the child div of inner should appear. I'm trying to write code for that but the best I can come up with is showing all inner divs. Only the child inner div should appear.
Please help me with the code for this, I will appreciate it, thank you :)

https://jsfiddle.net/wyeqgfjz/#&togetherjs=6wNtokkegm

HTML:

<div class="mydiv">
<div class="inner"></div>
</div>

<div class="mydiv">
<div class="inner"></div>
</div>


CSS:

.mydiv {
background: #ccc;
padding: 40px;
margin-bottom: 40px;
}

.inner {
background: red;
padding: 40px;
}


jQuery:

var inner = $('.mydiv .inner'),
mydiv = $('.mydiv');
inner.hide();
mydiv.each(function() {
$(this).on('hover', function() {
$(this).find(inner).toggle();
});
});

Answer Source

There is no hover event, the events you want are mouseenter and mouseleave instead.
However, jQuery has a hover() method that combines the events for you.

Note that you don't have to use a loop, jQuery iterates internally for you.

var inner = $('.mydiv .inner'),
    mydiv = $('.mydiv');
    
inner.hide();

mydiv.hover(function() {
  $(this).find(inner).toggle();
});
.mydiv {
  background: #ccc;
  padding: 40px;
  margin-bottom: 40px;
}

.inner {
  background: red;
  padding: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mydiv">
  <div class="inner"></div>
</div>

<div class="mydiv">
  <div class="inner"></div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download