JQuery changing background color of unordered list item

1.3k Views Asked by At

I have an unordered list and i would like to change the background color of each item when that item is selected(items in list are link tags) here is the JQuery code that I have so far.

$("#cat").focusin(function(){
    $("#cat").css("background-color", "#1796cf");
});

$("#cat").focusout(function(){
    $(this).css("background-color", "#333333");
});

#cat is set as ID in the html for each item in my list. This works but only works on the first item in the unordered list. Please help me get this to work on every item in my list.

3

There are 3 best solutions below

2
On BEST ANSWER

Id should be unique use class instead of id

$(".cat").focusin(function(){
    $(this).css("background-color", "#1796cf");
});

$(".cat").focusout(function(){
    $(this).css("background-color", "#333333");
});
0
On

Try another way

$('.cat').focus(function() {
       $(this).css("background-color", "#1796cf");
    }).blur(function() {
        $(this).css("background-color", "#333333");
 });
4
On

ok after your comment I've re-made my answer, here are the things you need in order to make it work:

HTML:

<ul class="selectable">
    <li><a href="#">text</a></li>
    <li><a href="#">text</a></li>
    <li><a href="#">text</a></li>
</ul>

CSS:

.selectable li {
    background-color: #333;
}

.selectable li.cat {
    background-color: #1796cf;
}

.selectable li a {
    color: white;
}

.selectable > li > a {
    display: block;
}

and finally some JQuery to do the magic:

$('.selectable > li > a').click( function( e ) {
    //prevent click from anchors, you can avoid this step if you need them
    e.preventDefault();
    //look for any previous class asigned
    $('.selectable').find('li').removeClass('cat');
    //add class to the li
    $(this).parent().addClass('cat');
});

link to the updated fiddle