Change Background Color CSS with Timer JQuery

13,829

Solution 1

I dont know if you mean animated as in fading to the next, but heres a simple quick example of changing the color every 2 seconds. First example does not require jQuery.

Live Demo

function changeColor(curNumber){
    curNumber++;

    if(curNumber > 4){
        curNumber = 1;
    }
    document.body.setAttribute('class', 'color' + curNumber);
    setTimeout(function(){changeColor(curNumber)}, 2000);  
}

changeColor(0);

Update animating color

Second example requires Jquery UI if you wish to fade between classes or background colors.

Demo 2

function changeColor(element, curNumber){
    curNumber++;

    if(curNumber > 4){
        curNumber = 1;
    }

    element.addClass('color' + curNumber, 1000);

    // So previous classes get removed.
    element.attr('class', 'color' + curNumber);

    setTimeout(function(){changeColor(element, curNumber)}, 2000);  
}

changeColor($('#testElement'), 0);

Solution 2

UPDATE

I'm sure there are better ways to do this, but just to show you a simple way of accomplishing this...

http://jsfiddle.net/UnsungHero97/QLPbW/5/


You want to use the window.setInterval() function...

window.setInterval(rotateBG, 1000); // 1000 = 1 second

function rotateBG() {
    // logic to rotate background
}

I hope this helps.

Share:
13,829
RCNeil
Author by

RCNeil

Just making sure the internet works.

Updated on June 04, 2022

Comments

  • RCNeil
    RCNeil almost 2 years

    I was hoping someone could show me efficient JQuery to animate between 4 background colors in a div class.

    I would like these events to be triggered by time, not click or hover. I've seen posts on hover and toggle, but as someone not very proficient in JQuery, I didn't feel comfortable copying and pasting parts here and there.

    Thank you