Question

I'm using jQuery to add a class "selected" to a div when a user clicks on it (it adds a red border to a thumbnail). At the same time I want to remove the class from a previously selected div.

I can get this to work if all the divs are siblings, but other divs in the document remain selected. The page I'm designing and developing requires that the divs can't all be siblings. How can I remove the class "selected" on a previously selected div anywhere in the document, not just the siblings?

You can view and edit my example on jsfiddle: http://jsfiddle.net/3s4dM/6/

jQuery:

$(".thumbnail").click(function() {
    $(this).addClass("selected").siblings().removeClass("selected");
})

CSS:

.thumbnail {
    background: #dddddd;
    width: 42px;
    height: 42px;
    margin-bottom: 5px;
}

.thumbnail:hover {
    cursor: pointer;
}

.thumbnail.selected {
    width: 36px;
    height: 36px;
    border: 3px solid #C72D30;
}

HTML:

<section>

    <div class="thumbnail"></div>

</section>

<section>

    <div class="thumbnail"></div>

</section>

<section>

    <div class="thumbnail"></div>
    <div class="thumbnail"></div>
    <div class="thumbnail"></div>

</section>
Was it helpful?

Solution

You can use a combined selector to get all div elements with the classes thumbnail and selected then remove the selected class from it.(Since you are again adding selected to current thumbnail ignore that also using not())

$(".thumbnail").click(function() {
    $('.thumbnail.selected').not(this).removeClass("selected")
    $(this).addClass("selected");
})

Demo: Fiddle

OTHER TIPS

You can remove class selected from all current elements that has .selected and add class selected to clicked .thumnail element:

$(".thumbnail").click(function () {
    $('.selected').removeClass("selected");
    $(this).addClass("selected");
});

Updated Fiddle

Try this?

$(".thumbnail").click(function() {
    $('.selected').removeClass('selected');
    $(this).addClass("selected");
});

If there all div's you can do it like this.

$(".thumbnail").click(function() {
    $('div').removeClass('selected');
    $(this).addClass("selected");
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top