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").click(function(){
if ($('.cat').is(":selected")) {
$(this).css("background-color", "#1796cf");
} else {
$(this).css("background-color", "#333333");
}
});
HTML code is as follows:
<ul class="categories">
<li class="cat"><a href="#">K-12</a></li>
<li class="cat"><a href="#">Higher Education</a></li>
<li class="cat"><a href="#">Healthcare</a></li>
<li class="cat"><a href="#">Corporate</a></li>
<li class="cat"><a href="#">Recreation</a></li>
<li class="cat"><a href="#">Community</a></li>
<li class="cat" style="border:none"><a href="#">Faith Based</a></li>
</ul>
.cat
is a class for each item in my unordered list. Problem is it is always running my else statement. What selector should I use to reference when the link is the one that is selected at the time? I tried using focuson() instead of click() but with other elements on the page this will not work the way I want it to.
Approach 1 - Minimal change
Explanation - "li" element does not have selected property,hence your code was not working. You can simply check the background-color property and toggle it.
Approach 2 - Some what more change but cleaner code
You can also simplify your code.
Update your script to
Add this in your css
With the above, you will have all the li's having background of #333333. And click event toggles the another class which overrides the background-color property to #1796cf. The only thing you need to make sure is .background_selected style should be after .cat style in your css file.
I hope both the approaches are clear.
New Requirement - Select Only One element at a time.
Please note, this will do nothing if you click on selected element. However, if you need to toggle the class on selected element too and I want to unselect it on click, then you will need following code.