JQuery: I have a problem with a changement of class on click

andybullet profile image AndyBullet ・1 min read

Hi guys! I have a problem.
In this code there are two clickable paragraph: "7" and "8".
And by jquery, when I click one of them, the background of the button change, and after 2 seconds the first background returns.
The probelm is that it works only for a click: when I run the code, I click "7" and the function works, but if immediately after I click "8" it doesn't work. And vice versa if I start with "8" on run.
It's a weird problem, can you help me to find a solution?


Editor guide

Here is how I would do it:
Also, I don't recommend using different functions if the action is the same.
Instead, getting your paragraphs by class name instead of id is better.


Yes, I had already corrected the code using that method.


As has already been suggested, you want to use setTimeout.

A couple other things: instead of using a third CSS class, you can add and then remove the second background. Also, you can consolidate how things are set up quite a bit. Attach one handler to document.ready, which sets up your click handlers. Then you can set up the immediate and the delayed actions at once.

I had to tinker with the code a bit to get a copy that would run without reference to your images in the CSS, but everything is basically the same. Here's the code with the changes I'd suggest: pastebin.com/JRiixP7e


Use setTimeout instead of setInterval


In this way?

}, 2000));

}, 2000));


You should also combine all the $(document).ready(functions into one. 😉