qadenza
qadenza

Reputation: 9293

Add-remove class dynamically

<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.

FIDDLE

Upvotes: 0

Views: 97

Answers (2)

zessx
zessx

Reputation: 68790

You should :

  • Use the second argument of hover() for hover out
  • Keep a trace of your initial active item

Updated 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');
    }
);

Updated Fiddle

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

sushil bharwani
sushil bharwani

Reputation: 30187

$('.m2Pass').hover(function(){
    $('.m2Act').removeClass().addClass('m2Pass');
    $(this).removeClass().addClass('m2Act');
},function(){

 // revert the properties in this function

}
)

Upvotes: 2

Related Questions