cyberoy
cyberoy

Reputation: 373

Select item from unordered list in html

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>

Upvotes: 3

Views: 26873

Answers (5)

Rick Hitchcock
Rick Hitchcock

Reputation: 35680

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'.

Upvotes: 11

Serhiy Chupryk
Serhiy Chupryk

Reputation: 438

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

.items li:active {
    color: green;
}

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

Upvotes: 0

Elliott
Elliott

Reputation: 2225

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>

Upvotes: -1

Satwik Nadkarny
Satwik Nadkarny

Reputation: 5143

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>

Upvotes: 1

Bak
Bak

Reputation: 262

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/

Upvotes: 1

Related Questions