Jason
Jason

Reputation: 3

jquery list confusion

I'm a new to the jQuery world and I'm having a problem that I just can't solve. I have an unordered list with multiple li's. I'm trying to make it so when the user clicks a row, the bg color on the row changes. And when another row is click, that row's bg color changes and the previous on goes back to the default color. This is my code so far:

$('.allVideos ul li').hover(function(){
   $(this).css('background','#c7f1f2');
}, function(){
   $(":not($(this))").css('background','');
});

Unfortunately it isn't working as planned. Can anyone explain to me what I am doing wrong?

Thanks

Upvotes: 0

Views: 39

Answers (2)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

this will work ,

$('.allVideos ul li').click(function(){

   $(".allVideos ul li").not($(this)).css('background','');
   $(this).css('background','#c7f1f2');
});

Upvotes: 3

mu is too short
mu is too short

Reputation: 434665

You want to use the not filter, not the :not selector:

$('li').click(function() {
    $(this).css('background-color', '#c7f1f2');
    $('li').not(this).css('background-color', '');
});

Demo: http://jsfiddle.net/ambiguous/ZUk88/

When you say li:not($(this)) then you're trying to select all <li> elements that aren't <$(this)> elements and that doesn't make sense; similarly for li:not(this).

You could also remove the background color from all the list items and then add it to the one you want:

$('li').click(function() {
    $('li').css('background-color', '');
    $(this).css('background-color', '#c7f1f2');
});

Demo: http://jsfiddle.net/ambiguous/L6ZNz/

Also, your question talks about clicking but your code talks about hovering.


If you have colors already attached to your <li> elements and you want to restore those colors when someone clicks another <li>, then you should just add and remove a CSS class to change the color. A bit of CSS:

.hilight {
    background-color: #c7f1f2 !important;
}

and some jQuery:

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

Demo: http://jsfiddle.net/ambiguous/ZJpNa/

Upvotes: 2

Related Questions