How can I highlight the selected list item using jquery?

I have several elements in the list and want to highlight the one that the user clicks, applying some css style, possibly background color, etc.

My HTML looks like this:

<ul class="thumbnails"> <li> <a href="#" class="thumbnail"> <img class="giftthumb" src='thumb1.jpg' alt=""> <span class="gifttitle">Thumb1</span> </a> </li> <li> <a href="#" class="thumbnail"> <img class="giftthumb" src='thumb2.jpg' alt=""> <span class="gifttitle">Thumb3</span> </a> </li> <li> <a href="#" class="thumbnail"> <img class="giftthumb" src='thumb3.jpg' alt=""> <span class="gifttitle">Thumb3</span> </a> </li> </ul> 

jQUery to retrieve the selected item:

 $('.thumbnail').click(function(e) { e.preventDefault(); ??? }) 
+6
source share
4 answers

You can use jQuery's class management methods (namely addClass() and removeClass() in this case) to add a class to the selected element and remove the same class from all other elements (if you want only one selected at a time).

 //save class name so it can be reused easily //if I want to change it, I have to change it one place var classHighlight = 'highlight'; //.click() will return the result of $('.thumbnail') //I save it for future reference so I don't have to query the DOM again var $thumbs = $('.thumbnail').click(function(e) { e.preventDefault(); //run removeClass on every element //if the elements are not static, you might want to rerun $('.thumbnail') //instead of the saved $thumbs $thumbs.removeClass(classHighlight); //add the class to the currently clicked element (this) $(this).addClass(classHighlight); }); 

Then in your CSS just add:

 .highlight { background-color: cyan; font-weight: bold; } 

jsFiddle Demo

This is a better solution than changing CSS properties directly from jQuery / Javascript (for example, using the .css() method), since separating the problems will make your code more manageable and readable.

+14
source
 $('.thumbnail').click(function(e) { e.preventDefault(); $(this).css('background-color', 'red'); }) 
+1
source

Your??? will be:

 $('.thumbnail').removeClass('selected'); $(this).addClass('selected'); 

Then all you have to do is define your "selected" css class.

+1
source

If active as constant is not required here: CSS way:

 li:focus{ background: red; } li:active{ background: gold; } 
 <ul> <li tabindex="1">Item 1</li> <li tabindex="1">Item 2</li> <li tabindex="1">Item 3</li> </ul> Now click <b>here</b> and see why it not persistent. 

in some situations the above may be useful - select only the current click-active & hellip;

+1
source