Reputation: 2342
I'm trying to achieve an effect in which a background color is pulsated when a condition is me. So I have:
<div class="box">...</div>
.box {
background-color: #fff;
transition: background-color 0.5s ease-out;
}
.box.active {
background-color: #ccc;
}
So now I want to use jQuery to add and remove that class a couple times to create a background-color pulsating effect. Something like:
$('.box').addClass('active').delay(1000).removeClass('active').delay(1000).addClass('active');
This, in theory, should create the pulsating effect but it doesn't. What happens is that the 'active' class is added and is never removed or added again. It's almost like the first 'removeClass' is never triggered.
I'm missing something, but not sure what. Maybe it has something to do with CSS transition timing, but they should be independent of each other, right?
Thanks for any ideas.
Upvotes: 7
Views: 10827
Reputation: 926
basically if you want it to pulsate forever you should use setInterval() i set up an example for you here http://jsfiddle.net/UftRT/
function pulssate() {
if ( $('.box').hasClass('active') ) {
$('.box').removeClass('active')
} else {
$('.box').addClass('active')
}
}
window.setInterval(function() { pulssate(); },1000);
if you want it to stop just set the interval in a variable then call window.clearInterval(int), like this
int = window.setInterval(function() { pulssate(); },1000);
Upvotes: 2
Reputation: 3983
The delay
function is actually only used for animations. Adding and removing a class is not an animation, but you can use the queue
method or setTimeout
function to achieve what you want.
This question has a lot of good replies on another thread that might make an interesting read for you.
Upvotes: 1
Reputation: 116
Try to achieve this effect with CSS3 Animations.
@-webkit-keyframes pulsate
{
0% {background-color: #fff;}
50% {background: #ccc;}
100% {background: #fff;}
}
Then apply the keyframes to the box
element
.box{
animation: pulsate 2s infinite;
}
http://jsfiddle.net/taltmann/jaQmz/
Upvotes: 4
Reputation: 5216
Delay only works with animations, not adding and removing classes. Also, you can pulsate using keyframes in CSS:
@keyframes pulse {
50% { background-color: #ccc }
}
.box {
animation: pulse .5s ease-out 2;
}
Upvotes: 16
Reputation: 40737
I think this is what you need, a function that calls itself every x seconds and alters a css property, see live demo.
var state = true;
function changeColor() {
state = !state;
if(state){
$("div").css("background","red");
}else{
$("div").css("background","blue");
}
setTimeout(function () {
changeColor();
}, 1000);
}
changeColor();
Upvotes: 0