Reputation:
This is my code:
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
})
function animatePress(currentColor) {
$("." + currentColor).addClass("pressed");
}
setTimeout(animatePress,2000);
So when I press the button on my website, the "pressed" class is applied (to make it darker) but the setTimeout doesn't work to make it revert back to its original colour. I followed the layout for the functions carefully so I don't know why it's not working. Thanks in advance
Edit: This is my jquery script in my HTML, could it be because of that?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" charset="utf-8"></script>
Upvotes: 3
Views: 84
Reputation: 14570
You setTimeout
is outside of the click which will not execute like that as its does not know where the userChoosenColor
is:
Try this code should just work fine.
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
setTimeout(function() {
animatePress(userChosenColor)
}, 2000);
})
function animatePress(currentColor) {
$("." + currentColor).toggleClass("pressed");
console.log('I am Called')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Click Me</button>
Upvotes: 0
Reputation: 166
This should work:
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
setTimeout(() => animatePress(userChosenColor),2000);
})
function animatePress(currentColor) {
$("." + currentColor).toggleClass("pressed");
}
Upvotes: 1