Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background color of elements every 5s using jquery? [duplicate]

Would like to ask for help regarding this one. I made 4 boxes with 2 background colors (red & green) without using html.

Here's my jsfiddle: https://jsfiddle.net/2bk1Ldg2/3/

How can I make a way to identify the existing background color css to change it alternately within 5sec (red to green & green to red).

Didn't know what's the best query to search regarding this kind of problem. Your awesome answers are a big help to my learning. Appreciate it a lot!

$(document).ready(function() {
function() {
    $( ".div1, .div3" ).animate({backgroundColor: 'red'
  }, 5000)};
});
like image 837
Kobe Bryan Avatar asked Jan 21 '26 17:01

Kobe Bryan


1 Answers

You should use setInterval() to repeat your code for seconds. Because you added background of element in style attribute, you can use HTMLElement.style to get name backgroud color.

setInterval(function(){  
    $("div").each(function(){
        this.style.background = this.style.background == "green" ? "red" : "green";
    });
}, 5000);

setInterval(function(){  
  $("div").each(function(){
    this.style.background = this.style.background == "green" ? "red" : "green";
  });
}, 1000);
div { height: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background: green"></div>
<div style="background: red"></div>
<div style="background: green"></div>
<div style="background: red"></div>
like image 56
Mohammad Avatar answered Jan 24 '26 06:01

Mohammad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!