I have a list of element ids that are randomly generated. The elements already exist, I am not creating or removing them. I just need to select random ones via their id:
stripped out HTML:
<div id="circle1"></div>
<div id="circle2"></div>
<button id="start">Start<button>
some simple JS/jQuery:
var circles = [];
function getRandomCircle() {
return "circle" + Math.floor((Math.random() * 3) + 1);
}
function flashCircles() {
for (var i = 0; i < circles.length; i++) {
setTimeout(function() {
$("#" + circles[i]).fadeTo("slow", 1, function() {
$("#" + circles[i]).fadeTo("slow", 0.5, function() {});
});
}, i * 1000);
}
}
$("#start").on("click", function() {
circles.push(getRandomCircle());
circles.push(getRandomCircle());
circles.push(getRandomCircle());
flashCircles();
});
The #circle elements are not getting selected, and thus not fading in and out. I reach the setTimeout()
call, I don't get inside the callback for the initial selector. The circles.push(getRandomCircle())
calls work as expected. Nothing changes if I remove them and initialise the circles array instead. I don't think it's the array notation because if I run the following after setTimeout()
and within the loop, the elements are selected as expected:
if ($("#" + circles[i]).length) {
console.log("selected")
} else {
console.log("not selected")
}
The only thing that works is a hard coding the id to call:
$("#"+"circle1").doStuff();
I had this working, originally. getRandomCircle()
contained a for-loop that populated the array. Nothing else has changed.
What's happening here? Array notation worked before, it works here when checking if something is selected, but it not working within setTimeout()
, despite the fact it was working before. All code is wrapped in a $("document").ready()
call.