I want to have 5 lists such than when any of them is clicked, it turns to green and turn the other lists to black if any of them is green.
Here's my list:
<div id="menu">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
I have written the jquery. However, it's not concise, as I have to select $('#menu li:first-child').. and $('#menu li:nth-child(2 to 5)')..
Please check out the demo and let me know the easiest way you have to get this done
DEMO:
http://jsfiddle.net/t7L6d7b4/
To change the background color of the button, use the CSS background-color property and give it a value of a color of your taste. In the . button selector, you use background-color:#0a0a23; to change the background color of the button.
The way you do it:
var $li = $('#menu li').click(function() {
$li.removeClass('selected');
$(this).addClass('selected');
});
with this CSS for selected item:
li.selected {
color: green;
}
Don't ever use css
method for such things, this is very obtrusive approach which requires you to modify JS code when you want to change styling. If tomorrow you decide to add a background image to selected item, what will you have to do if you go with .css
approach? You should use classes for this, in this case you write JS once and forget about this. Styles are for CSS, UI logic is for JS.
Here is a demo:
var $li = $('#menu li').click(function() {
$li.removeClass('selected');
$(this).addClass('selected');
});
li.selected {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
You can just do
$('li').click(function(){
$('li').css('color','black');
$(this).css('color', 'green');
});
DEMO The above is simple, but you can create classes and add/remove it using addClass/removeClass.
One solution is this:
$("ul > li").on("click", function(){
$("ul li").css("color", "black");
$(this).css("color", "green");
});
li{
list-style:none;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With