HTML <ul> | Change specific <li> color onclick and other <li> s to the same default <ul> color
I want to have 5 lists, for example if when you click on any of them it turns green and the rest of the lists 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 wrote JQuery. However, this is not concise as I have to choose$('#menu li:first-child').. and $('#menu li:nth-child(2 to 5)')..
Please check out the demo and let me know the easiest way to do this.
DEMO:
source to share
How do you do it:
var $li = $('#menu li').click(function() {
$li.removeClass('selected');
$(this).addClass('selected');
});
with this CSS for the selected element:
li.selected {
color: green;
}
Never use a method css
for things like this, it's a very intrusive approach that requires changing the JS code when you want to change the style. If tomorrow you decide to add a background image to the selected element, what do you need to do if you go with an approach .css
? You have to use classes for this, in this case you write JS once and forget about it. Styles for CSS, UI logic for JS.
Here's 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>
source to share
One solution:
$("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>
source to share
You can do it with CSS too! Like this. Behavior. It will show green when clicked, then it will go 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>
source to share
Here is the code without using any library or frameworks. You can achieve this with JavaScript.
<div>
<ul>
<li class="active">one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
</ul>
</div>
The script goes here ....
function myFunction(e) {
var elems = document.querySelector(".active");
if(elems !==null){
elems.classList.remove("active");
}
e.target.className = "active";
}
source to share