chris
chris

Reputation: 37480

How can I alternate between two background colors?

I'm building a calendar, and one of the requirements is to highlight certain days by setting the background-color CSS property.

However, there are occasions when one day needs to have two different colors: for example, when a payday happens on a holiday.

Is there a way to alternate between two different background colors? We're using jquery, and I've looked at the cycle plugin but that seems to be complete overkill for what I need.

This will cycle through once, but I'd like it to be continuous:

$(".toggleBG").animate({ backgroundColor: "#FFFF66" }, 2000, function() {
    $(".toggleBG").animate({ backgroundColor: "#99CCFF" }, 2000)
});

Upvotes: 2

Views: 1668

Answers (5)

Nate B
Nate B

Reputation: 6344

var changeColors = setInterval(function() { 
     $(".toggleBG").toggleClass('color2');
}, 2000);

Then, create a CSS rule for each background color:

div.color1 { 
     background-color: #FFFF66;
     -moz-transition: all 1s ease-in-out;
     -webkit-transition: all 1s ease-in-out;
     transition: all 1s ease-in-out;
}
div.color1.color2 { background-color: #99CCFF; }

The transitions will make the color change smooth instead of "flashing," at least in newer browsers that support it.

Upvotes: 0

alpjef
alpjef

Reputation: 57

only the jquery UI library supports color alternating, so when you download the jQueryUI library from http://www.jqueryui.com and add the script to your webpage, it should work

Upvotes: 0

Adam Merrifield
Adam Merrifield

Reputation: 10407

function toggleBg(){
    if($('.toggleBG').css('backgroundColor') == '#FFFF66'){
        $('.toggleBG').css('backgroundColor', '#99CCFF');
    }else{
        $('.toggleBG').css('backgroundColor', '#FFFF66');
    }
    setTimeout(toggleBg, 2000);
}
$(function(){
    toggleBg();
});

Upvotes: 1

Authman Apatira
Authman Apatira

Reputation: 4054

There are probably other ways to do this as well, but you can use the timeout function to keep the code going:

function flip() {
    $(".toggleBG").animate( 
    { backgroundColor: "#FFFF66" }, 2000, function() {
    $(".toggleBG").animate({ backgroundColor: "#99CCFF" }, 2000) 
    });
    setTimeout( flip(), 1 );
}

Upvotes: -1

Eric
Eric

Reputation: 97681

This ought to work:

var animate1, animate2;
var elem = $(".toggleBG");

animate1 = function() {
    elem.animate({ backgroundColor: "#FFFF66" }, 2000, animate2)
}
animate2 = function() {
    elem.animate({ backgroundColor: "#99CCFF" }, 2000, animate1)
}

animate1();

Each function uses the other as the callback to animate.


The easiest way to stop the animation is:

animate1 = animate2 = undefined

Upvotes: 4

Related Questions