Angad Dubey
Angad Dubey

Reputation: 5452

add / remove class from list item

I have some list items displayed with a PHP loop. I want to add a class to the list item that's clicked, then remove the class from this item and add it to the next item that is clicked or if clicked anywhere else.

I have tried:

$j('.list_item').on("click", function() {

        $j(this).addClass("active_card");

    }).on("blur", function() {

        $j(this).removeClass("active_card");

});

It adds the class, but does not remove it when clicked on another item.

HTML: I'm sorry, these aren't the list items as mentioned earlier, but are still displayed inside a PHP loop.

<div id="item_list_wrapper">
<div class="list_item">...</div>
<div class="list_item">...</div>
<div class="list_item">...</div>
<div class="list_item">...</div>
</div>

Upvotes: 1

Views: 992

Answers (2)

Jason P
Jason P

Reputation: 27012

I think this will get you what you want:

http://jsfiddle.net/S7EK9/

$j('.item_list').on("click", function (e) {
    $j('.active_card').removeClass('active_card');
    $j(this).addClass("active_card");
    e.stopPropagation();
})

$j(document).on('click', function () {
    $j('.active_card').removeClass('active_card');
});

If you click one of your .item_list elements, that will be highlighted. If you click anywhere else, the active_card class will be removed.

Upvotes: 0

Bic
Bic

Reputation: 3134

Depending on what is clicked, it won't draw focus and subsequently won't trigger a blur event. You're better off using a class selector to get the item.

$j('.item_list').on('click', function () {
    $j('.active_card').removeClass('active_card');
    $j(this).addClass('active_card');
});

Upvotes: 5

Related Questions