Raihan
Raihan

Reputation: 4001

Issue with jQuery class toggling

I have some list items. Followings are some scenarios:

  1. If I click any list item it become selected and add a class .slected
  2. If I click another list item previous list become unselected and new list become selected
  3. If I click the list item which already been selected it become unselected

FIDDLE

Those scenarios working perfectly. But problem occurs when I press the Edit link. I don't wanted to Unselect during Edit mode. It should remain selected during I perform edit actions.

How I can do this matching those 3 conditions ? what wrong I am doing here ? Any help with this will save my day. Thanks in advance.

JS

$("body").on('click', '.list-group-item', function() {  

    if ($(this).hasClass('selected')) {
       $(this).removeClass('selected');
     } else {
      $(".list-group-item").removeClass('selected');
       $(this).addClass('selected');
     }


});

Upvotes: 2

Views: 57

Answers (2)

abl
abl

Reputation: 5958

$("body").on('click', '.list-group-item', function(ev) {    
    var target = ev.target; // Topmost clicked element
    if(!$(target).is(".btn")){ // If click wasn't on a button
        $(this).toggleClass('selected');
        $(this).siblings().removeClass('selected');
    }       
});

Fiddle

Upvotes: 2

Niko Bellic
Niko Bellic

Reputation: 2550

Add the line

event.stopPropagation();

as follows:

$(".btn-link").click(function () {
    event.stopPropagation();
    $(this).parent('.view-mode').hide();
    $(this).parent('.view-mode').siblings('.edit-mode').show();
});

Upvotes: 0

Related Questions