user1688604
user1688604

Reputation: 113

JQuery hover multiple elements one function

I have three divs with hidden inner divs, when you rollover over each div its inner div should display and when you rollout it hides again.

for example, I rollover div1, div1 inner appears, I rollout, div1 inner disappears.

However when I move my mouse from div1 directly over div2, both are treated as rollout, eg div1 inner disappears (as it should), div2 inner appears(as it should) but then instantly disappears with div1 inner.

Apart from writing separate functions for div1 2 and 3 I'm not sure what to do, any help much appreciated!!

jsfiddle.net/user1688604/UZpEH/3

var box = $("#box1,#box2,#box3");
var inner = $(".item");


$(box).hover(function() {
    $(this).find(inner).stop(true,true).css({"left":"20px"}).animate({"top":"-10px", "opacity": "1"},400);

}, function() {
    $(this).find(inner).stop(true,true).animate({"top":"-20px", "opacity": "0"},400, function() {
        $(inner).css({"left":"-9999px", "top":"0"});
        });
});



<div id="box1">
<div class="item"></div>
</div>

#box1, #box2, #box3 {
            width: 300px;
            float: left;
            margin-right: 20px;
            position: relative;
            }


            .item {
                width: 151px;
                height: 49px;
                padding: 5px 10px 0;
                opacity: 0;
                position: absolute;
                    top: 0;
                    left: -9999px;
                }

Upvotes: 3

Views: 19280

Answers (3)

Pandian
Pandian

Reputation: 9126

Try like below... it will help you..

Keep Same class name for all the DIV.. and try the below..

Fiddle Example : http://jsfiddle.net/RYh7U/96/

HTML :

<div class="divBox">
    Show Div1
<div class="item">
Div 1    
</div>
</div>

<div class="divBox">
    Show Div 2
<div class="item">
    Div 2

</div>
</div>

<div class="divBox">
    Show Div 3
<div class="item">    
    Div 3
</div>
</div>

JQuery :

$('.item').hide(); 
$('.divBox').hover(function() { 
    $(this).children('.item').show();     
}, function() { 
    $(this).children('.item').hide(); 
});

Upvotes: 0

Kaizen Programmer
Kaizen Programmer

Reputation: 3818

Add a class to the box divs (same class for each)

<div id="box1" class="box">
    <div class="item"></div>
</div>

jQuery

$(".box").hover(function(){
   $(this).find(".item").stop(true,true).css({"left":"20px"}).animate({"top":"-10px", "opacity": "1"},400);
},function(){
   $(this).find(".item").animate({"top":"-20px", "opacity": "0"},400, function() {
       $(this).css({"left":"-9999px", "top":"0"});
   });
});

Upvotes: 6

EnterJQ
EnterJQ

Reputation: 1014

On Whichever div or any fields , you wanna provide hover function just call then with same class name ,then trigger your function by referring that class name.

Upvotes: 0

Related Questions