I have a list with 4 items, each item has a specific background color set in the style attribute.
<div class="list">
<div style="background: red"></div>
<div style="background: blue"></div>
<div style="background: green"></div>
<div style="background: yellow"></div>
</div>
I would like to change the background color of each item to the color of the next item in the list. The HTML code above should be changed to:
<div class="list">
<div style="background: yellow"></div>
<div style="background: red"></div>
<div style="background: blue"></div>
<div style="background: green"></div>
</div>
I have tried implementing this code, but it is not working.
$(".list > div").each(function(i){
var index = i == 0 ? 3 : i-1;
this.style.background = $(".list > div").eq(index)[0].style.background;
});
The current code sets the color of the last item to all items. What could be the issue?
setInterval(function(){
$(".list > div").each(function(i){
var index = i == 0 ? 3 : i-1;
this.style.background = $(".list > div").eq(index)[0].style.background;
});
}, 1000);
.list > div { height: 50px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
<div style="background: red"></div>
<div style="background: blue"></div>
<div style="background: green"></div>
<div style="background: yellow"></div>
</div>