user715564
user715564

Reputation: 1690

jQuery .off isn't working with .on

I have a jQuery accordion box that contains a right arrow to the right of each link. When the user clicks on the link, the arrow turns into a down arrow and the content expands. When the user clicks on the same link, the arrow turns back into the right arrow and the content is hidden (typical accordion style). To get the arrows to switch, I am using jQuery .on and switching out a class on a span element. Everything works just fine expect when I try to remove the event with .off. Here is my script:

<script>
function handleClick(event) {
    $('#arrow').removeClass('icon-angle-right').addClass('icon-angle-down');
};

$('.panel-heading a').on('click', handleClick);
$('.panel-heading a').off('click', handleClick);
</script>

Right now, nothing works. If I remove the .off line than the span will switch classes but obviously not switch back when clicked again.

Upvotes: 0

Views: 151

Answers (3)

Moob
Moob

Reputation: 16184

.on() binds an event and .off() unbinds it. See http://api.jquery.com/off/

Upvotes: 0

George Yates
George Yates

Reputation: 1247

By unbinding the event handler, you're not achieving what you want. Because you're binding the click handler then immediately unbinding it which is why nothing works if you keep the line in. You need to be running the handler every time to change out the class, the handler is what modifies the DOM, and it needs to do that both in expanding and contracting the accordion.

toggleClass() will successfully do what you're looking to achieve., so remove the off() line and switch out your function for:

function handleClick(event) {
    $('#arrow').toggleClass('icon-angle-right').toggleClass('icon-angle-down');
};

As another note, I would have a default state that would be with the arrow angled right for that item, then an open class I would toggle that would override the default state. That way you're only maintaining one class. But that's an architecture nitpick.

Upvotes: 2

Pevara
Pevara

Reputation: 14310

Not sure why you are trying to remove the handler again. Would it mot make more sense to do something like this:

<script>

$('.panel-heading a').on('click', function() {
     if ($(this).hassClass('icon-angle-right') {
          $(this).removeClass('icon-angle-right').addClass('icon-angle-down');
     } else {
          $(this).addClass('icon-angle-right').removeClass('icon-angle-down');
     }
});
</script>

Or am I misunderstanding the question?

Upvotes: 2

Related Questions