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 ???

5
  • 2
    Just as a tip - This would suffice: .on('click',functionA);. The same for the other function. Commented Jun 23, 2016 at 17:23
  • You attached the event handler before the element received the new class. You need to look for delegation. Commented Jun 23, 2016 at 17:25
  • Your functions are missing the keyword function. E.g. function functionA () {... Commented Jun 23, 2016 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 . Commented Jun 23, 2016 at 17:29
  • Have you noticed that you are missing the equal sign between var functionB function () ? Commented Jun 23, 2016 at 17:32

1 Answer 1

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'); 
    });
Sign up to request clarification or add additional context in comments.

2 Comments

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()});
That was just to give a direction on what you need to do. You can definitely change it based on your need.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.