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
  • 3,267
  • 5
  • 40
  • 91
  • 2
    Just as a tip - This would suffice: `.on('click',functionA);`. The same for the other function. – melancia Jun 23 '16 at 17:23
  • You attached the event handler before the element received the new class. You need to look for _delegation_. – melancia Jun 23 '16 at 17:25
  • Your functions are missing the keyword `function`. E.g. `function functionA () {...` – j08691 Jun 23 '16 at 17:26
  • Well, disregard this error, I've edited the question for the right syntax regarding keyword function. In my real code, everything is correct . – Edgar Navasardyan Jun 23 '16 at 17:29
  • Have you noticed that you are missing the equal sign between var functionB function () ? – Franco Jun 23 '16 at 17:32

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,367
  • 1
  • 15
  • 23
  • 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