Reputation: 5203
Hi I'm trying to make a row of divs blink, but one div should blink at a time.(not all the divs should blink at the same time [i could do that])..
kind of like the way a traffic light works. each light is part of a row of lights and each light turns on and off one at a time going through a loop. in my case the blinking is meant to remind the users that the divs or clickable.
I put each box in an array but I couldn't figure out how to change the color of each box in a loop. I guess a way to solve this is by adding and removing a classes that contains the colors and it should do that after 1 or 2 seconds so setInterval should come in to play. I couldn't figure it out.
but here is my sad code
var arr =[];
$(".boxes").each(function(){
arr.push($(this));
});
function bgChange(){
for(i = 0; i < arr.length; i++){
arr[i].addClass("red");
}
}
setInterval(bgChange, 2000);
});
I'm looking to forward to seeing the creative ways that you guys could come up with to make this work.
JSFIDDLE Thank You in advanced
Upvotes: 1
Views: 6758
Reputation: 37763
You could do this using toggleClass
to set the class for the current box:
var boxes = $(".boxes");
var current = 0;
function animate() {
boxes.each(function(index) {
$(this).toggleClass("red", index == current);
});
current = (current + 1) % boxes.length;
setTimeout(animate, 1000);
};
animate();
Upvotes: 0
Reputation: 48972
Try:
var arr = $(".boxes");
var current = 0;
function bgChange(){
if (arr.length > 0){
//Remove class of all items
arr.removeClass("red");
//Set Class of current item
arr.eq(current).addClass("red");
//Increase the current index
current = (current + 1) % arr.length;
}
}
setInterval(bgChange, 2000);
Upvotes: 3
Reputation: 89750
You can try doing it with the below code. Demo
$(document).ready(function () {
var arr = [];
var i = 0;
$(".boxes").each(function () {
arr.push($(this));
});
function bgChange() {
for (var count = 0; count < arr.length; count++) {
if (i == count) arr[count].css('background-color', 'red');
else arr[count].css('background-color', 'white');
}
i++;
if (i === arr.length) i = 0;
}
setInterval(bgChange, 2000);
});
EDIT: If you want to do it by using CSS classes, modify the for loop to be like below:
for (var count = 0; count < arr.length; count++) {
if (i == count) arr[count].addClass('red');
else arr[count].removeClass('red');
}
Upvotes: 2
Reputation: 388316
Try
var $boxes = $(".boxes");
function bgChange(){
var $active = $boxes.filter('.red'), $next = $active.next('.boxes');
if(!$next.length){
$next = $boxes.first();
}
$active.removeClass('red');
$next.addClass('red');
}
setInterval(bgChange, 2000);
Demo: Fiddle
Upvotes: 1