Skip to content Skip to sidebar Skip to footer

How Can I Randomize The Value Of Css Attributes Using Jquery?

I'm trying to use jquery to make a css selector randomize one of its values on an html element. I've gotten as far as randomizing the selector for all of the elements (cycling thro

Solution 1:

You can use jQuery.each() function to specify individual colors: http://jsfiddle.net/qaF24/

$(document).ready(function(){
    var colors = ["#CCCCCC","#333333","#990099"];                
    $('.bars').each(function() {
        var rand = Math.floor(Math.random()*colors.length);
        $(this).css("border-left-color", colors[rand]);
    });
});

Solution 2:

http://jsfiddle.net/RMR42/1/

var colors = ["#CCCCCC", "#333333", "#990099"];
var bars = document.getElementsByClassName('bars');
for (var i = 0; i < bars.length; i++) {
    bars[i].style.borderLeftColor = colors[Math.floor(Math.random() * colors.length)];
}

Maybe a vanilla solution will help somebody. Faster, without more code.

Solution 3:

The jQuery selector ('.bars') is selecting all elements of the class 'bar'. Of course it's going to set them all the same.

I would recommend instead assign an id to the parent element and then use the .children() selector to iterate through each <li> and assign a color.

something like

<ulid="bars"><li><a>Marathon Men and Women</a></li><li><a>Marathon Men and Women</a></li><li><a>Marathon Men and Women</a></li><li><a>Marathon Men and Women</a></li><li><a>Marathon Men and Women</a></li></ul><script>
$(document).ready(function(){
  var colors = ["#CCCCCC","#333333","#990099"],rand;                
  var ligroup = $('#bars').children();
  for (var i=0,len=ligroup.length;i<len;i++) {
       rand = Math.floor(Math.random()*colors.length);
       $(ligroup[i]).css("border-left-color", colors[rand]);
  }

});
</script>

Solution 4:

$(document).ready(function () {
var bars = document.getElementsByClassName('bars');
for (var i = 0; i < bars.length; i++) {
    bars[i].style.borderLeftColor ="#"+genColor();
}
});

Random color generator for each Li : http://jsfiddle.net/RMR42/2/

you have to use some sort of looping through all the similar class elements if you want each individual to be different and random.

reference: https://gist.github.com/wfreeman/1158409

Post a Comment for "How Can I Randomize The Value Of Css Attributes Using Jquery?"