Search code examples
jquerydom-traversal

jQuery hidden div using hover showing all hidden divs


I'm sure it's been asked, but I couldn't find a solution to my issue. I have a class that is named the same across 3 divs. This class is being hidden using css. The issue is that when I hover over 1 of the divs, all 3 show the hidden at the same time. I just want the element that I am hovered on to show. I think I should use .each() but I'm not sure how it all fits together.

CSS

.background-hover {
    display: none;

HTML:

    <div class="home-get-started">
   <-- first--><div class="home-get-started">
            <!-- image-->
            <img src="image.png">
              <!-- hover hidden state -->               
                <div class="background-hover">
                <div class="home-btn">Text</div>
                </div>
            </div>

<--second --> <div class="home-get-started">
            <!-- image-->
            <img src="image.png">
              <!-- hover hidden state -->               
                <div class="background-hover">
                <div class="home-btn">Text</div>
                </div>
            </div>
    </div>

jQuery:

$(".home-get-started").hover(
function () { $('.background-hover').css({"display":"block"}); },
function () { $('.background-hover').css({"display":"none"}); }
);

Solution

  • You are showing/hiding all elements with class background-hover. What you probably want is to do this only to descendants of the element which triggered the event...

    You can use find() to query the DOM for the descendants of a certain element (this in our case).

    $(".home-get-started").hover(
        function () { $(this).find('.background-hover').show(); },
        function () { $(this).find('.background-hover').hide(); }
    );
    

    jsFiddle Demo

    Be aware the in some cases both Texts will show at the same time - that's because your wrapper div also has the home-get-started class so the hover handlers will fire for that element too.