Reputation: 9293
<div class='m2Act' id='edu'>Edu</div>
<div class='m2Pass' id='ref.php'>Ref</div>
<div class='m2Pass' id='con.php'>Con</div>
<div style='clear:both'></div>
css
.m2Act, .m2Pass{
float:left;
margin:5px;
cursor:pointer;
}
.m2Act{
background:yellow;
}
.m2Pass{
background:red
}
js
$('.m2Pass').hover(function(){
$('.m2Act').removeClass().addClass('m2Pass');
$(this).removeClass().addClass('m2Act');
})
All this works, but when the cursor is away - I need to have a previous state of each div. This doesn't happen. divs remains in the new, hovered state. I already tried with mouseenter
and mouseleave
without success.
Upvotes: 0
Views: 97
Reputation: 68790
You should :
hover()
for hover outUpdated code :
<div class='m2Act initial' id='edu'>Edu</div>
<div class='m2Pass' id='ref.php'>Ref</div>
<div class='m2Pass' id='con.php'>Con</div>
$('.m2Pass').hover(
function(){
$('.m2Act').removeClass('m2Act').addClass('m2Pass');
$(this).removeClass('m2Pass').addClass('m2Act');
},
function(){
$('.m2Act').removeClass('m2Act').addClass('m2Pass');
$('.initial').removeClass('m2Pass').addClass('m2Act');
}
);
EDIT :
As mentioned by Simon in comments, you can use toggleClass()
instead of removeClass()
and addClass()
, to simplify your code :
$('.m2Pass').hover(
function(){ $('.m2Act').add(this).toggleClass('m2Act m2Pass'); },
function(){ $('.m2Act, .initial').toggleClass('m2Act m2Pass'); }
);
Upvotes: 1
Reputation: 30187
$('.m2Pass').hover(function(){
$('.m2Act').removeClass().addClass('m2Pass');
$(this).removeClass().addClass('m2Act');
},function(){
// revert the properties in this function
}
)
Upvotes: 2