tctc91
tctc91

Reputation: 1363

addClass to an image when clicked. If another image is clicked, remove that class and add it to the new image

I have a list containing four images. Each image should only have one active class at any given time. (similar to radio buttons).

My code so far supports this fine: http://jsfiddle.net/tctc91/HyHgp/

var themeChooser = $('.themeChooser ul li img');
themeChooser.click(function() {
    if(!themeChooser.hasClass('themeSelected')) {
        $(this).addClass('themeSelected');        
    } else {
        $(this).removeClass('themeSelected');
    }
});

My problem is that when the .themeSelected class is already active, It will not work if you click on a different image. I need it so IF it is already active and you click on a different image, it removes the existing class and adds it to the new image.

Thanks!

Upvotes: 0

Views: 776

Answers (1)

Jamiec
Jamiec

Reputation: 136154

The simple addition of $('.themeSelected').removeClass('themeSelected'); inside your click handler achieves what you want.

Live example: http://jsfiddle.net/sT9jE/


Edit: Not quite so simple, the above stops a re-click on the selected element unselecting. Therefore you actually need this addition:

if(!$(this).hasClass('themeSelected'))
    $('.themeSelected').removeClass('themeSelected');

See this Live example: http://jsfiddle.net/HM5DF/

Upvotes: 1

Related Questions