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 m
You can do this with CSS too! Like this. Behavior - On clicking it will show green, then it will turn back to black.
li:active{
color:green;
}
<div id="menu">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
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>
It works for me with jquery version 2.1.1, Please try this
$(document).on('click', '#menu li', function(){
$('.#menu li').removeClass('selected');
$(this).addClass('selected');
});
And add this in CSS file.
#menu li.selected {
background-color: rgb(2, 95, 191);
}
Here is code without using any library or frameworks. You can acheive this using javascript.
<div>
<ul>
<li class="active">one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
Script goes here ....
function myFunction(e) {
var elems = document.querySelector(".active");
if(elems !==null){
elems.classList.remove("active");
}
e.target.className = "active";
}
css goes here....
li.active {
color: green;
}