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>
This should work:
$(".btn").click(function() {
var userChosenColor = $(this).attr("id");
animatePress(userChosenColor);
setTimeout(() => animatePress(userChosenColor),2000);
})
function animatePress(currentColor) {
$("." + currentColor).toggleClass("pressed");
}
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.