user2281858
user2281858

Reputation: 1997

jQuery - show and hide div on hover using closest selector

I am trying to simply achieve the show/hide feature on hover using the hover function of jquery.

However not able to show and hide the particular div. When I hover over the current span tag I want only the current(closest) div to hide and the closest or next possible div to be shown.

But currently since the class names are same, it is showing all the divs

FIDDLE HERE

HTML structure:

<div class="parentCat">
    <div class="imageContainer">
        <span class="hoverEffect">Some Image</span>
    </div>
    <div class="showContainer">
        <span>New Image</span>
    </div>
</div>
<div class="parentCat">
    <div class="imageContainer">
        <span class="hoverEffect">Some Image</span>
    </div>
    <div class="showContainer">
        <span>New Image</span>
    </div>
</div>

Upvotes: 0

Views: 1345

Answers (2)

Matt Greenberg
Matt Greenberg

Reputation: 2330

If you want this effect, you need to alter your code. The div which has the hover event can't be one that you are hiding. It is also good practice to nest the related divs INSIDE of a parent div. I believe this is what you are looking for.

HTML

  <div class="ca hoverEffect" style="height:40%">
      <div class="imageContainer">
          <span>Some Image</span>
      </div>
      <div class="showContainer">
          <span>New Image</span>
      </div>
  </div>

JS

$('.hoverEffect').hover(function () {
    $(this).find('.imageContainer').hide();
    $(this).find('.showContainer').show();

}, function () {
    $(this).find('.imageContainer').show();
    $(this).find('.showContainer').hide();
});

Working jsfiddle

Upvotes: 1

Fenton
Fenton

Reputation: 251082

If you shift the event to the parent element, everything becomes simpler:

$('.ca').hover(function () {
    $('.imageContainer', this).hide();
    $('.showContainer', this).show();

}, function () {
    $('.imageContainer', this).show();
    $('.showContainer', this).hide();
});

Updaated working example.

Upvotes: 3

Related Questions