Jiroscopes
Jiroscopes

Reputation: 555

On hover fadeToggle with multiple divs

So I have some divs with an img inside. Above the img is a div that is hidden, but will appear on hover of the img. I know how to make it work, but I want it to be simpler, this is more for my own learning. I want it to work the same as I have, just simpler and cleaner jquery/javascript.

$('#img-1').hover(function(){
    $('#overlay-1').stop().fadeToggle(400);
});
$('#img-2').hover(function(){
  $('#overlay-2').stop().fadeToggle(400);
});

Here is it in action: JsFiddle

Upvotes: 0

Views: 144

Answers (2)

maembe
maembe

Reputation: 1300

 $('.img').hover(function(){
    $(this).find('.overlay').stop().fadeToggle(400);
 });

the $(this) keyword is the object that you're calling hover() on. So we find() children of the thing that was hovered with the class .overlay

Upvotes: 3

Michael Coker
Michael Coker

Reputation: 53674

You can do this with pure CSS, using :hover on .img and transition with opacity on .overlay

.img {
  position: relative;
}
.img > img {
  width: 200px;
  height: 200px;
}
.overlay {
  background-color: #f7c845;
  z-index: 100;
  position: absolute;
  height: 200px;
  width: 200px;
  opacity: 0;
  transition: opacity .4s;
}
.overlay > p {
  text-align: center;
  color: #212121;
  padding: 20px 40px;
}
.img:hover .overlay {
  opacity: 1;
}
<div class="img" id="img-1">
  <div class="overlay" id="overlay-1">
    <p>Hello World!</p>
  </div>
  <img src="https://s-media-cache-ak0.pinimg.com/736x/bf/4e/40/bf4e4067252227bd3f758bba7dcee2ff.jpg" alt="image">
</div>
<div class="img" id="img-2">
  <div class="overlay" id="overlay-2">
    <p>Hello World!</p>
  </div>
  <img src="https://s-media-cache-ak0.pinimg.com/736x/bf/4e/40/bf4e4067252227bd3f758bba7dcee2ff.jpg" alt="image">
</div>

Upvotes: 1

Related Questions