Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
142
rated 0 times [  148] [ 6]  / answers: 1 / hits: 33725  / 12 Years ago, fri, march 8, 2013, 12:00:00

I have several items in a list and want to highlight the one a user clicks on by applying some css style, maybe a 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 selected item:



$('.thumbnail').click(function(e) {
e.preventDefault();

???

})

More From » jquery

 Answers
15

You could use jQuery's class management methods (namely addClass() and removeClass() in this case) to add a class on the selected item and remove the same class from all the other items (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 (with the .css() method for example), because separation of concerns will make your code more manageable and readable.


[#79725] Thursday, March 7, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregorio

Total Points: 362
Total Questions: 95
Total Answers: 93

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
gregorio questions
Fri, Apr 8, 22, 00:00, 2 Years ago
Mon, Sep 6, 21, 00:00, 3 Years ago
Sun, Sep 13, 20, 00:00, 4 Years ago
;