Herland Cid
Herland Cid

Reputation: 574

Issue to apply hover with jquery when elements share the same class

I have an issue to apply hover with jquery when elements share the same class. This works pretty fine when using just CSS, but as long as JQuery appears, it changes everything.

CSS

.btn {
background:#ccc;
padding:10px;
}
.btn:hover {
background:red;
padding:10px;
}

HTML

<a class="btn">Button 1</a><br /><br /><br />
<a class="btn">Button 2</a><br /><br /><br />
<a class="btn">Button 3</a><br /><br /><br />

<div id="paragraph"><p>Everything works fine with normal css Hover...</p></div>

<input type="button" id="btnchange" value="Change to JQuery Hover, blue color" />

JQuery

$('#btnchange').bind('click', function() {

                $(".btn").hover(function(){
                $(".btn").css({background: "blue"});
                },function(){
                $(".btn").css({background: "#ccc"});
                }); 

                $("#paragraph").html('<p>But then, when applying jquery hover, things work unexpectedly</p>');

});

Here is the live Fiddle

I don't have to modify the HTML code, just JQuery.

Upvotes: 2

Views: 184

Answers (3)

cssyphus
cssyphus

Reputation: 40038

Revised jsFiddle

The jQuery code, as you wrote it, selects all elements of class "btn" and turns them all blue. You need to select only the element that is triggering the hover event and turn that one blue. Therefore,

Change this:

$('.btn').css({background: "blue"});

to this:

$(this).css({background: "blue"});

Upvotes: 7

Coder
Coder

Reputation: 7076

Change ".btn" inside hover to $(this)

JQuery Demo

$('#btnchange').bind('click', function() {

                    $(".btn").hover(function(){
                    $(this).css({background: "blue"});
                    },function(){
                    $(this).css({background: "#ccc"});
                    }); 

                    $("#paragraph").html('<p>But then, when applying jquery hover, things work unexpectedly</p>');

});

Upvotes: 2

MacK
MacK

Reputation: 2181

Use the $(this) selector inside the hover function to target the actual hovered element:

$(".btn").hover(function(){
   $(this).css({background: "blue"});
},function(){
   $(this).css({background: "#ccc"});
}); 

Upvotes: 2

Related Questions