1

The issue is best described by example:

JS:

$(function () {
   $('.classA').on('click', function () { functionA() );
   $('.classB').on('click', function () { functionB() });
} 

var functionA = function()
{
    alert('I am function A');
    $('.classA, .classB').toggleClass('classA classB');
}

var functionB = function ()
{
    alert('I am function B');
    $('.classA, .classB').toggleClass('classA classB');
}

The problem is simply put but hard for me to fix: as expected, after pressing class A div, function A is called, class A is toggled to class B, but next time I press the same div, function A is still called, whereas I expect function B to be called then. I am doing something wrong ???

Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

3

You can delegate the event from the document to the element with the appropriate class then apply jQuery's toggleClass function to that event.

   $(document).on('click','.classA', function () { 
       alert('I am function A');
       $('.classA, .classB').toggleClass('classA classB');
    });

   $(document).on('click','.classB', function () { 
      alert('I am function B');
     $('.classA, .classB').toggleClass('classA classB'); 
    });
Community
  • 1
  • 1
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • This completely solved my question, but! It is partially off-topic, and yet if I write $(document).on('click','.classA', functionA() ); then functionA is triggered on document load event. This problem goes away if I change it to ....'.classA', function() {functionA()}); – Edgar Navasardyan Jun 23 '16 at 17:48
  • That was just to give a direction on what you need to do. You can definitely change it based on your need. – DinoMyte Jun 23 '16 at 17:52