2

I have a list of items vertically. I want to select item from the list. Also, selected item will get green or any color. At a time, only one item can be selected from list. I can create the list. But, no idea how to make it selective and change color after selection by clicking mouse. Do I need to use any CSS for that?

<div class="items">
  <ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
  <ul>
</div>
Serhiy Chupryk
  • 438
  • 2
  • 5
  • 15
cyberoy
  • 313
  • 1
  • 7
  • 18

5 Answers5

8

Give each li element a tabindex, and add this CSS:

li:focus {
  background: lightgreen;
}
<div class="items">
  <ul>
    <li tabindex="1">Item1</li>
    <li tabindex="1">Item2</li>
    <li tabindex="1">Item3</li>
  <ul>
</div>

To do this in plain JavaScript:

  1. Add a click event listener to the ul element.
  2. If the event's target is an li element:
    2a. If there's an existing li that's selected, remove its class.
    2b. Add a selected class to the event's target.

document.querySelector('ul').addEventListener('click', function(e) {   // 1.
  var selected;
  
  if(e.target.tagName === 'LI') {                                      // 2.
    selected= document.querySelector('li.selected');                   // 2a.
    if(selected) selected.className= '';                               // "
    e.target.className= 'selected';                                    // 2b.
  }
});
.selected {
  background: lightgreen;
}
<div class="items">
  <ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
  <ul>
</div>

Note that LI must be capitalized in e.target.tagName === 'LI'.

Rick Hitchcock
  • 34,132
  • 4
  • 45
  • 75
1

The HTML

<div class="items">
  <ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
  <ul>
</div>

And the Jquery

$(".items ul li").click(function(){
    $(".items ul li").css("color","inherit");
    $(this).css("color","green");
});

http://jsfiddle.net/74g21org/1/

Bak
  • 252
  • 1
  • 3
  • 11
1

You can use jquery as such:

$("ul li").on("click", function () {
    $("ul li").removeClass('selected');
    $(this).attr('class', 'selected');

});
.selected {
    background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
    <li>Item1</li>
    <li>Item2</li>
    <li>Item3</li>
</ul>
Satwik Nadkarny
  • 4,944
  • 2
  • 22
  • 40
0

You can do it with plain html and css like this:

.items li:active {
    color: green;
}

http://jsfiddle.net/b8jwnfgp/1/

Serhiy Chupryk
  • 438
  • 2
  • 5
  • 15
-1

To expand on Bak's response, you will need to use Javascript to apply the styles such as color.

jQuery is probably the easiest way to go about doing as he suggested. This is a good place to start: https://learn.jquery.com/about-jquery/how-jquery-works/

Also, don't forget to close your list item tags:

<li>Item1< / li>
Elliott
  • 1,715
  • 20
  • 22