Reputation: 1
I'm trying to change the color of a selected li item by class by cobbling together different parts of examples and obviously missing something.
If it isn't clear I'm a noob to css and jquery.
Thanks for looking.
html
<div class="menuwrapper">
<ul>
<li><a href="#">Item 1</a>
</li>
<li><a href="#">Item 2</a>
</li>
<li><a href="#">Item 3</a>
</li>
<li><a href="#">Item 4</a>
</li>
<li><a href="#">Item 5</a>
</li>
</ul>
css
/* Define the body style */
body {
font-family:Arial;
font-size:12px;
}
/* Remove the margin, padding, and list style of UL and LI components */
.menuwrapper ul, .menuwrapper ul li {
margin:0;
padding:0;
list-style:none;
}
/* Apply background color and border bottom white and width to 150px */
.menuwrapper ul li {
background-color:#7f95db;
border-bottom:solid 1px white;
width:150px;
cursor:pointer;
}
/*Apply the background hover color when user hover the mouse over of the li component */
.menuwrapper ul li:hover {
background-color:#6679e9;
position:relative;
}
/* Apply the link style */
.menuwrapper ul li a {
padding:5px 15px;
color:#ffffff;
display:inline-block;
text-decoration:none;
}
/* Apply the background select color when the li component is selected */
.menuselected li {
background-color:#6679e9;
border-bottom:solid 1px white;
width:190px;
cursor:pointer;
}
jscript
var main = function () {
$(".menuwrapper ul li").click(function () {
$(this).addClass('menuselected'); /*this applies class but does not change style of li element */
//$(this).css("background-color","#ffaa99"); //this works when uncommented
})
}
$(document).ready(main);
link to code: jsfiddle
Upvotes: 0
Views: 68
Reputation: 1
The CSS definition has been covered, you should add that li
’s weight, like:
.menuwrapper li.menuselected{
background-color:#6679e9;
border-bottom:solid 1px white;
width:190px;
cursor:pointer;
}
Upvotes: 0
Reputation: 25392
Your .menuselected
is being applied to the li, not the ul.
Your CSS target should just be .menuwrapper ul li.menuselected
You could also change the JS to add the class to the parent ul.
$(this).parent().addClass("menuselected");
Also: you may consider clearing the .menuselected
class before assigning it to the clicked li. That way, you'll only ever have one selected li.
$(".menuselected").removeClass("menuselected");
$(this).addClass("menuselected");
Unless of course you want to be able to select multiple, in which case, you may be looking for toggleClass()
:
$(this).toggleClass("menuselected");
Upvotes: 0
Reputation: 388316
The problem is the css definition. You are adding the class to the li
element so the css definition .menuselected li
is wrong because it looks for a li
child which is inside a .menuselected
element.
Also you have a problem with css specificity, the rule .menuwrapper ul li
is more specific then just li.menuselected
so you can use
.menuwrapper ul li.menuselected {
background-color:#6679e9;
border-bottom:solid 1px white;
width:190px;
cursor:pointer;
}
Demo: Fiddle
Upvotes: 1