1

I have a span with some text that changes every time the user clics a button. I need the color of it to change with every clic (I have the colors in an array like this: var colorArray = ["red","blue","red","red","green","blue","green","red"])

The array is not fixed as I read it from DB.

Any idea on how to do this via javascript (it's for a phonegap project)

Sascuash
  • 3,661
  • 10
  • 46
  • 65

3 Answers3

2

Every time you click on the button you can take the first element of your array and put it at the end of it, so it's a loop.

After with jQuery .css() function you can put the first color of the array to your span.

Code should look like this :

var colorArray = ["red","blue","green"];
$('button').click(function(){
    $('span').css({"color":colorArray[0]});
    colorArray.push(colorArray.shift());
});

See this Fiddle for more details

SauriolJf
  • 412
  • 2
  • 10
1

You can use jQuery and the css() function. Please have a look at the documentation for this function at http://api.jquery.com/css/#css2 (there are also some examples in the end of the site). In the end you will have something like this:

$("span#id").css("color", target_color);

Instead of span#id you have to use the CSS selector for the target <span> element and target_color has to be the color of your array, you want to use.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Stephan Kulla
  • 4,739
  • 3
  • 26
  • 35
1

If you want pure js Here is the js code:

<script>
  var color = {
    currentColor: 0,
    colorArray: ["red","blue","red","red","green","blue","green","red","orange"],
    changeColor: function(){
      document.getElementById('span1').style.color = color.colorArray[color.currentColor];
      if (color.currentColor < color.colorArray.length-1){
        color.currentColor++;
      }else{
        color.currentColor = 0;
      }
    }
  };
</script>

Here ir your html:

<input type="button" value="change color" onclick="color.changeColor()">

<span id="span1"></span>
Newton
  • 47
  • 9