-2

For some reason when I add a class to an element using Jquery I cannot perform a function using the class name just added:

 $('.openslidecontent .arrow.off').click(function() {  
        $('.openslidecontent,.rightwrapper .arrow').removeClass('off')
        $('.openslidecontent,.rightwrapper .arrow').addClass('on');
      return false;
     });

    $('.openslidecontent .arrow.on').click(function() {   // THIS FUNCTION DOES NOT EXECUTE
        $('.openslidecontent,.rightwrapper .arrow').removeClass('on');
        $('.openslidecontent,.rightwrapper .arrow').addClass('off');
      return false;
     });
Omar
  • 786
  • 3
  • 13
  • 34
  • 2
    Not sure about your issue, but why not just use `toggleClass()` instead and you'd be able to merge those two callbacks into one. See: http://api.jquery.com/toggleclass/ – Scott Marcus Dec 06 '16 at 16:14
  • You're binding to an element with the class `on`, but that class is added dynamically. To keep things the way you have them, you'd have to do `$('.openslidecontent .arrow').on('click', '.on', function() ...`. However, I would follow Scott's advice and use `toggleClass()`. – Gavin Dec 06 '16 at 16:15
  • You would need to use a delegated event handler as you're changing classes at run time. As @ScottMarcus says though, using `toggleClass()` is a much better solution entirely. – Rory McCrossan Dec 06 '16 at 16:15
  • I do not want to use toggleClass, because I need to a different classname to close with to perform a different function. – Omar Dec 06 '16 at 16:20
  • That makes no sense. Can you explain what you actually want to do, as the answer below fits logic of the code example you provided perfectly. – Rory McCrossan Dec 06 '16 at 16:20
  • Rory, read my update. Like this I have to perform the same function with the toggle of on and off, but I need to perform a different function on the off. – Omar Dec 06 '16 at 16:28
  • The answer does work as described, I must have another problem. – Omar Dec 06 '16 at 16:30

1 Answers1

5

The event listener is only attached to existing elements. You can switch to event delegation to have the listener react on newly created elements too

$(document).on('click', '.openslidecontent .arrow', function() {
    $('.openslidecontent,.rightwrapper .arrow').toggleClass('on off');
})

Also, as Rory commented, you can just change your code to use toggleClass() and hook the event to both at the same time

baao
  • 71,625
  • 17
  • 143
  • 203