Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery cycle - add then remove css class - infinite loop

How do I use jQuery to infinitely add then remove a CSS class on a set of 4 li's.

Basically, see this simple fiddle (without any jquery): http://jsfiddle.net/kHsvN/

I want to cycle through the boxes to change the css of a box, flip back to original css, then go on to the next one etc etc...

Any help appreciated!

like image 503
Ben Davis Avatar asked Oct 07 '22 11:10

Ben Davis


2 Answers

$(document).ready(function() {
   window.setInterval(function() {
        $("#topboxesmenu li a").each(function() {
            $(this).css("background", get_random_color());
    });
  }, 1000);
});

function get_random_color() {
   var letters = '0123456789ABCDEF'.split('');
   var color = '#';
   for (var i = 0; i < 6; i++ ) {
     color += letters[Math.round(Math.random() * 15)];
   }
   return color;
}

This example uses a random colour, but could easily be changed to .addClass() in the .each part.

JS Fiddle (Live Example)

http://jsfiddle.net/kHsvN/6/

Random color generator in JavaScript

like image 195
Darren Avatar answered Oct 09 '22 01:10

Darren


Try this:

jQuery(document).ready(function() {
    window.setInterval(function() {
            var oldBox = jQuery('#topboxesmenu li.active');
            if(oldBox.length == 0 || oldBox.next().length == 0)
            {
                    oldBox.removeClass('active');
                jQuery('#topboxesmenu li:first-child').addClass('active');
            }
            else
                oldBox.removeClass('active').next().addClass('active');
    },2000);
});

It will cycle through the boxes, adding an active class to them one after the other.

http://jsfiddle.net/gKEmL/

like image 26
bardiir Avatar answered Oct 08 '22 23:10

bardiir