0

How can I loop through this array which changes the css background color chronologically rather than randomly and reverse through the same array when the back button is clicked?

http://jsfiddle.net/qK2Dk/

$('#right').click(function(){

var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
var bgImage = bgImages[Math.floor(Math.random() * bgImages.length)];
var image = bgImage;

var element = document.getElementById('bgImage');
element.style.background  = image; // IE fallback

});


<a class="left carousel-control" id="left" href="#carousel" data-slide="prev">
<span>Left</span>
</a>
<br />
<a class="right carousel-control" id="right" href="#carousel" data-slide="next">
<span>Right</span>
</a>

<div id="bgImage">
test
</div>
1
  • 2
    Start with 0 and store its array index. Change image accordingly Commented Dec 6, 2013 at 13:05

1 Answer 1

1

Try this

var ix=0;
$('#right').click(function(){

    var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
    var bgImage = bgImages[ix];
    if(ix<bgImages.length){
         ix++;
    }

    var image = bgImage;
    var element = document.getElementById('bgImage');
    element.style.background  = image; // IE fallback

});

$('#left').click(function(){

    var bgImages = ["#fff", "#f00", "#000", "#f0f", "#ccc", "#ddd", "#eee", "#bbb"];
    if(ix>0){
         ix--;
    }
    var bgImage = bgImages[ix];


    var image = bgImage;
    var element = document.getElementById('bgImage');
    element.style.background  = image; // IE fallback

});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.