views:

51

answers:

2

Hi, basically i have a page on my site with boxes that slide to reveal a background color. I want this background color to be random on load of page by adding a class to the element, eg .blue, .green etc...

I have created this code and as you may notice this randomly sorts the color class and applies to the element, this works for the first 6 elements however this page in particular has 12 elements i wish this to apply to, so my question is how do i apply a random selection of the variable classes to all ".portfolio ul li a "? Would it need to have some form of a repeat?

This is my script ..

function randCol() {
return (Math.round(Math.random())*7); }

$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];
classes.sort( randCol );
$('.portfolio ul li a').each(function(i, val) {
    $(this).addClass(classes[i]);
});

})

This is my source code structure

<div class="portfolio">
<ul>
    <li>
       <a href="#">
         <img src="images/content/portfolio/sample1.png" height="175" width="294" alt="sample" class="front" />
         Text for behind the image                         
       </a>
    </li>


+3  A: 

Your randCol() comparison function doesn't really work. In the first place, such a function should return 1, -1 or 0 depending on whether the first term of the comparison is greater than, less than, or equal to (respectively) the second term.

Second, the code you have in there is apparently intended to reference your 6-element array, but as written it can return values as high as 7, which is 2 higher than the last index of the array. Better to do your randoming within the each() function literal, like so:

$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];

$('.portfolio ul li a').each(function(i, val) {
    var index = Math.floor(Math.random()*6); // highest value will be 5, lowest will be 0
    $(this).addClass(classes[index]);
});
Robusto
Perhaps use `var index = Math.floor(Math.random()*classes.length);` and then you can add any number of colours to the array without having to remember to change the factor.
Dave Anderson
Thats perfect, thanks very much for the explanation also I am very new to JScript.
XtremeGinn
@Dave Anderson, nice addition a good idea should i need to add new colors. Thanks
XtremeGinn
@Dave Andersion: Of course. This was merely an illustration of a technique, not a finished product.
Robusto
A: 

the above answer may result in repetition of clours I think this can fix it :)

$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];
var temp=0;
$('.portfolio ul li a').each(function(i, val) {
    if(temp==0){
    var index = Math.floor(Math.random()*6);}
    else{ 
    var index = Math.floor(Math.random()*6);
    index=temp+index;
    temp=index;}
});
pahnin