Startseite bisherige Projekte Tools/Snippets Bücherempfehlungen Publikationen Impressum Datenschutzerklärung

Random BackgroundNovember 2011

To add the Random Background effect to a page, you need to do the following steps:
Download a complete, working example in a zip-file.
  1. Create a simple JavaScript file with the following content. Note that this file contains the name of the images. Name the file "bg.js". Download Example
    function init(){
        
        var imgs = new Array(
        "lines.jpg", 
        "nemo.jpg", 
        "bsss.jpg"
        );
    
        var pos = Math.floor(Math.random()*imgs.length);
        
        var node = document.getElementById("banner");
        if (node){
            node.style.backgroundImage = "url(./"+imgs[pos]+")";
        }
        
    }
  2. Add the id "banner" to the element in the HTML-page that should have the changed background:
    <div id="banner" style="width:800px;height:200px"></div>
    
  3. Add the following text to the "head"-section of the html-file:
    <script type="text/javascript" src="bg.js"></script>
    
  4. Add onload="init()" to the "body"-tag of the html-file:
    <body onload="init()">
    
  5. A complete minimal HTML-file looks like this (Open Example):
    <html>
        <head>
            <script type="text/javascript" src="bg.js"></script>
        </head>
        <body onload="init()">
            <h1>Welcome to the example page</h1>
            <div id="banner" style="width:800px;height:200px"></div>
        </body>
    </html>
    
To change the available images, edit the JavaScript file. Add new images names after "bsss.jpg". Be aware that there must be a comma after each image-name except for the last one. Example:
var imgs = new Array(
    "CHANGED1.jpg", 
    "nemo.jpg", 
    "bsss.jpg",
    "NEW1.jpg",
    "NEW2.jpg",
    "NEW3.jpg"
    );
Impressum - Datenschutzerklärung