PiNg2Eiw PiNg2Eiw - 5 months ago 9
Javascript Question

Iterate over array on click

I'm creating an presentation.
There is a div element which does change the font-size a lot.
There are two buttons one should increase the color in the array and the
other one should decrease it.

html:

<input type="button" id="up" value="change color up">
<input type="button" id="down" value="change color down">

<div id="myValue">
VALUE
</div>


Jquery:

fancyColors = {
1: "#9c9e9f",
2: "#848e6f",
3: "#778861",
4: "#7da75d",
5: "#7fa433",
6: "#97bf0d"
};


$(function () {

var i;
var valuE = $('#myValue');
var getSize = $('#myValue').css("font-size");
var getColor = $('#myValue').css("color");
var down = $('#down');
var up = $('#up');



valuE.css("color", fancyColors[1]);
down.on("click",function() {
valuE.css("color", fancyColors[i]); // do i--
});


up.on("click", function() {
valuE.css("color", fancyColors[i]); // do i++
});
});


I had a for loop but that didn't work out for me.
I guess it should be pretty easy for a more experienced person.
Thanks for your time.

Answer

Make your html as

<input type="button" id="up" value="change color up">
<input type="button" id="down" value="change color down">
<div id="myValue">VALUE</div>

And your js:

var fancyColors = [
    "#9c9e9f",
    "#848e6f",
    "#778861",
    "#7da75d",
    "#7fa433",
    "#97bf0d"];


$(function () {

    var i = 0;
    var valuE = $('#myValue');
    var getSize = valuE.css("font-size");
    var getColor = valuE.css("color");
    var down = $('#down');
    var up = $('#up');



    valuE.css("color", fancyColors[1]);
    down.on("click", function () {
        valuE.css("color", fancyColors[i]);
        i++ // do i--
    });


    up.on("click", function () {
        valuE.css("color", fancyColors[i]);
        i++ // do i++
    });
});

Live Demo: http://jsfiddle.net/jY24d/