0

i am trying to use a simple method to invoke two functions based on the class name selector. it's a toggling function. so function A toggles the class name so that the class name matches the selector used for function B and vice a versa. The problem is even after the element class has been changed jquery seems to be firing the function for the old class.

example.

$(".unfav").bind('click', function (e) {
    $(this).toggleClass('unfav fav');
});

$(".fav").bind('click', function (e) {
    $(this).toggleClass('fav unfav');
});

if .fav was rendered originally and was triggered the consecutive clicks to the same element executes the .fav selector and not the .unfav selector. i tried using .on and doesn't seems to help.

How do it force jQuery to unbind the original trigger when class is changed?

DevZer0
  • 13,433
  • 7
  • 27
  • 51
  • Elements whose class changes dynamically are effectively the same as elements added dynamically. Use the same solution. – Barmar Jul 03 '14 at 11:17
  • I think things would work out better if you bound your events to the document with a selector scope... `$(document).on('click','#someSelector',callback)` . You shouldn't forget to unbind the events too ( `.off(...` ) – spender Jul 03 '14 at 11:17
  • 1
    use what solution? marked as a duplicate of what? – DevZer0 Jul 03 '14 at 11:17
  • @RajaprabhuAravindasamy It's essentially the same problem: the selector doesn't find all the matching elements when the page is first loaded. It doesn't matter whether it's because the elements haven't been added or because the classes are different. Either way, you use event delegation and it finds them when they match later. – Barmar Jul 03 '14 at 11:22
  • Thanks for the answer i try and let you know. @Barmar you say duplicate question but i don't even see a link to the original question. – DevZer0 Jul 03 '14 at 11:22
  • Above the question see "This question already has an answer here" – Barmar Jul 03 '14 at 11:22

0 Answers0