NineCattoRules
NineCattoRules

Reputation: 2428

How could I randomize the color attribute for an HTML element?

I have a grid of listed elements and my purpose is to randomize their loading background color. Until now all elements have the same background (thumbnailBackgroundColor) and this is set like this in the HTML file:

<head>
<script type="text/javascript" src="java/FWDIGP.js"></script>    

<script type="text/javascript">    

    FWDRLUtils.onReady(function(){    
        new FWDIGP({        
            thumbnailBackgroundColor:"#111111"     
            });
        });
</script>

The grid inside the body is coded like this:

<ul>
<li data-thumbnail-path="content/media/thumbnails/1.jpg" data-url="content/media/images/1.jpg" data-thumbnail-overlay-color="">
    <div>
        <p class="gallery1DecHeader">my description</p>  
    </div>                                
</li>
</ul>

and this is the function on JavaScript

this.setupPoolThumbs = function() {
        for (var o = 0; o < this.maxThumbs; o++) {
            FWDIGPThumb.setPrototype();
            e = new FWDIGPThumb(this, this.thumbnailTransitionType_str, this.thumbnailBackgroundColor_str, this.thumbnailOverlayBackgroundColor_str, n.thumbnailOverlayOpacity, n.showThumbnailOverlay_bl, this.isMobile_bl, n.showThumbnailIcon_bl, i.disableThumbnailInteractivity_bl);
            e.setVisible(false);
            e.addListener(FWDIGPThumb.MOUSE_OVER, this.onMouseOverHandler);
            e.addListener(FWDIGPThumb.MOUSE_UP, this.onMouseUpHandler);                
        }
    };

How could I randomize the thumbnailBackgroundColor attribute?

Upvotes: 0

Views: 163

Answers (1)

BenM
BenM

Reputation: 53198

Javascript is able to convert an integer into a base-16 (hex) string using the toString() function. You can use this particular function to generate a random number, and then in turn convert it a valid hex colour string.

Here's the basis code (courtesy of Paul Irish):

'#'+Math.floor(Math.random()*16777215).toString(16);

You can place this inline within the constructor, so your code will look as follows:

FWDRLUtils.onReady(function(){    
    new FWDIGP({        
        thumbnailBackgroundColor: '#'+Math.floor(Math.random()*16777215).toString(16)
    });
});

Upvotes: 2

Related Questions