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

github logo ・1 min read

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?

twitter logo DISCUSS (6)
markdown guide
 

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

 

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.

 

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

 
 

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));
});

 
 

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

Classic DEV Post from Apr 5

How NOT to ask for help

AndyBullet profile image

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️