DEV Community

AndyBullet
AndyBullet

Posted on

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

Hi guys! I have a problem.
https://pastebin.com/LxDbhGP3
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?

Top comments (7)

Collapse
 
simonced profile image
simonced • Edited

Here is how I would do it:
codepen.io/simonced/pen/ExxoMdm
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.

Collapse
 
andybullet profile image
AndyBullet

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

Collapse
 
paxfeline profile image
David Newberry • Edited

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

Collapse
 
aadityataparia profile image
Aaditya Taparia

Use setTimeout instead of setInterval

Collapse
 
andybullet profile image
AndyBullet

In this way?

$(document).ready(function(){
$("#7").click(setTimeout(function(){
$("#7").addClass("bg");
}, 2000));
});

$(document).ready(function(){
$("#8").click(setTimeout(function(){
$("#8").addClass("bg");
}, 2000));
});

Collapse
 
aadityataparia profile image
Aaditya Taparia

Yep

Collapse
 
testmynet profile image
TestMy.net

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