Reputation: 3654
I have simple a function that will look for a specific class ('.clickable') and add a class when it's clicked ('.last-clicked). I want to remove the ('.last-clicked') class from all other existing elements so there is only one item with that class.
$('.clickable').click(function(event) {
$('.clickable').removeClass('last-clicked');
$(event.target).addClass('last-clicked');
});
My function works but it seems silly to refer to $('.clickable') in the wrapper and the function. Is there a more efficient approach?
Upvotes: 0
Views: 49
Reputation: 40459
You can use .end()
...
//you can swap out event.target with this, if you like
$('.clickable').click(function(event) {
$('.clickable').removeClass('last-clicked').end().find(event.target).addClass('last-clicked');
});
DEMO: http://jsfiddle.net/dirtyd77/eU37H/3/
Upvotes: 1
Reputation: 12985
If the DOM isn't going to have clickable elements added or removed you can do this:
var $clickable = $('.clickable');
$clickable.click(function(event) {
$clickable.removeClass('last-clicked');
$(event.target).addClass('last-clicked');
});
Upvotes: 1
Reputation: 12441
If you are only using last-clicked
for these elements try:
$('.clickable').click(function(event) {
$('.last-clicked').removeClass('last-clicked');
$(event.target).addClass('last-clicked');
});
Upvotes: 3