tags:

views:

64

answers:

2

Hey guys, i'm having a problem with this little script. When i hover over the div "item" both divs shows the "dark-overlay". But i only want the dark-overlay there's inside the div i hover to show. How is that possible? thanks :)


.item {
position:relative;
width:680px;
height:140px;
}
.dark-overlay {
position:absolute;
width:680px;
height:140px;
background:url(images/bg.png) repeat;
display:none;
}

<div class="item">
   <div class="dark-overlay"></div>
   <img src="my image.jpg" />
</div>

<div class="item">
   <div class="dark-overlay"></div>
   <img src="my image.jpg" />
</div>

$(function() {
   $(".item").hover(function() {
      $(".dark-overlay").show();
   });
});
+2  A: 

You can find the .dark-overlay only inside the one you're hovering, like this:

$(function() {
   $(".item").hover(function() {
      $(this).find(".dark-overlay").show();
   });
});

Or, more likely, you want it to hide when leaving as well, in which case you should use .toggle() like this:

$(function() {
   $(".item").hover(function() {
      $(this).find(".dark-overlay").toggle();
   });
});

You can give it a try here, or add a bit of a fade animation, like this.

Nick Craver
Thank you very much, Nick! :)
Sebastian
Can you also tell me how i fade the .dark-overlay out when i don't hover the .item? :)
Sebastian
@Sebastian - check out the demos at the bottom of the answer :)
Nick Craver
Do note that this example uses jQuery 1.4.2. If you're using 1.3.2 the behaviour is a little different. I think the difference lies in the .hover() property but I'm not sure what they changed.
Litso
@Nick, thanks man! seems to work perfectly
Sebastian
@Litso, thanks for the note :)
Sebastian
@Litso - This is the same in 1.3.2, under the covers the event model changed a bit for *other* reasons, but nothing that affects this :)
Nick Craver
@Nick Craver, set the jQuery version in your jFiddle example to 1.3.2 and see what happens. In Chrome at least it does make a big difference.
Litso
+1  A: 

This should do the trick, the hover event handler takes two arguments (mouse in and mouse out), then just limit the .dark-overlay search to items within "this" (the current .item element)

$('.item').hover(
  function() { // Mouse in
    $('.dark-overlay', this ).fadeIn();
  },
  function() { // Mouse out
    $('.dark-overlay', this ).fadeOut();
  }
);
michael