Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML <ul> | Change particular <li> color onclick and other <li> in the same <ul> to default color

Tags:

jquery

css

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:

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/

like image 367
Edwin Avatar asked Oct 11 '14 17:10

Edwin


People also ask

How do I change the color of my click button?

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.


Video Answer


3 Answers

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>
like image 197
dfsq Avatar answered Oct 24 '22 07:10

dfsq


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.

like image 3
Amit Joki Avatar answered Oct 24 '22 09:10

Amit Joki


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>
like image 2
Alex Char Avatar answered Oct 24 '22 09:10

Alex Char