rob.m
rob.m

Reputation: 10571

Disable click on this

I am trying to disable click event only on current item with class

$(document).on( 'click', '.item', function() {
  $(".item").removeClass('is-expanded');
  $(this).addClass('is-expanded');
  $(".item").each(function(){   
    $(".item").click(true).css("cursor", "pointer");
    $(".is-expanded").click(false).css("cursor", "default");
  });

however, I can still click on item with class .is-expanded while it shouldn't as we only click on all other items without that class

Upvotes: 0

Views: 93

Answers (3)

user2225055
user2225055

Reputation: 83

If I understand, u need unbind

http://api.jquery.com/unbind/

$('.item').click(function() {
  $(".item").removeClass('is-expanded');
  $(this).addClass('is-expanded').unbind('click');
});

If u need ricovery the click, instead:

$( document ).ready(function() {
  $('.item').click(function() {
    if ($(this).hasClass('is-expanded')) {
      return false;
    } else {
      $(".item").removeClass('is-expanded');
      $(this).addClass('is-expanded');
    }
  });
});

http://embed.plnkr.co/c8WUE2iH1iKuJBvW8OG6/preview

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

If i understand your logic, you want:

$(document).on( 'click', '.item:not(.is-expanded)', function() {
    $(".item").removeClass('is-expanded');
    $(this).addClass('is-expanded');
});

And set cursor in CSS, as you should:

.item {
   cursor: pointer;
}

.item.is-expanded {
   cursor: default;
}

Upvotes: 2

David Thomas
David Thomas

Reputation: 253308

When using the on() method you're detecting the click, or other named event, on the element(s) to which the method is chained, and look to see where it originated. Once the even has already bubbled up it can't be prevented (because it's already happened).

You could, however, attach the event-listener to the elements themselves, and assess the current class:

$('.item').click(function(){
    if ($(this).hasClass('is-expanded')) {
        return false;
    }
    else {
        // do whatever
    }
});

Upvotes: 1

Related Questions