Domanda

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"}); }
);
È stato utile?

Soluzione

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.

Altri suggerimenti

How about this. you can use toggle

Demo

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

);

Also you have an extra <div class="home-get-started"> is that intended. If so hovering over that will trigger all of them.

If that is how it is then best bet is to use immediate child selector > to avoid opening of both.

$(".home-get-started").hover(
   function () {
       $('> .background-hover', this).toggle();
   }
);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top