Skip to content Skip to sidebar Skip to footer

How To Make Background Color Of Div Tag Keep Changing Using Jquery?

I am trying to change background of div tag continuously using for loop and rgb() values . following is my code written in sample.html:

Solution 1:

As this question is tagged as CSS, I would like to contribute a pure CSS solution to this, simply use CSS3 @keyframes and you can simply add colors to the element you want, can step the animation using % and also, you can use animation-iteration-count and set it to infinite. If you want to iterate it for limited times, just changed the infinite to whatever value you desire but make sure it's an integer.

Demo

.animate {
    height: 200px;
    width: 400px;
    border: 1px solid #000;
    -webkit-animation: animate_bg 5s;
    animation: animate_bg 5s;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
}

@keyframes animate_bg {
    0%   {background:red;}
    50%  {background:green;}
    100% {background:blue;}
}

@-webkit-keyframes animate_bg {
    0%   {background:red;}
    50%  {background:green;}
    100% {background:blue;}
}

This is introduced in CSS3 spec, so you can refer this link for browser support.


There are many polyfills available for the browsers which are not supporting CSS3 @keyframes, so you may need to use this if you are looking to support older browsers, if you don't care about the old one's, than you can use this without any hesitation.

Solution 2:

Everything seems fine besides the code where you set the CSS.

Change the code :

$("#sqr").css("background-color","rgb(r,g,b)");

To :

$("#sqr").css("background-color","rgb(" + r + "," + g + "," + b + ")");

This will now pass in the number values, i.e.

$("#sqr").css("background-color","rgb(254,254,254)");

Where as before it would have simply passed the values r,g,b because you placed them within a string.

Solution 3:

You can use .setInterval()

Enclose your code within a function called animate

var intervalID = window.setInterval(animate, 500);

Not sure correct this

$("#sqr").css("background-color","rgb(" + r +"," +g+"," +b +")");

Post a Comment for "How To Make Background Color Of Div Tag Keep Changing Using Jquery?"