Sheehan Alam
Sheehan Alam

Reputation: 60869

How can I change the background of a selected li in jquery?

I have an unordered list with a bunch of list items. I am setting the background of the selected <li> in its click:

$(this).animate({
          backgroundColor: '#0000FF'
}, 'fast');

When I click another <li>, I want to change its backgroundColor property, but I want the rest of the <li>s to default back to another color. This way, it looks like I am changing the selected state.

Upvotes: 2

Views: 1698

Answers (4)

run
run

Reputation: 1186

$('li').each.click(function(){
 $(this).css("backgroundColor", "");

});

Upvotes: 0

Simon Arnold
Simon Arnold

Reputation: 16167

I would use a mixe of classes and CSS transitions:

$('li').click(function(){)
    $('li.active').removeClass('active');
    $(this).addClass('active');
})

li{background:#fff; -webkit-transition:all 0.25s linear; -moz-transition:all 0.25s linear;}
li.active{background:#00f;}

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

$('ul li').click(function() {
    $(this).animate({backgroundColor:"#0000ff"},'fast')
        .siblings().animate({backgroundColor:"#000000"},'fast'); // or whatever other color you want
});

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

You could simply do the following:

$(this).siblings("li").css("backgroundColor", "");

Example on jsfiddle

Upvotes: 5

Related Questions