Function only runs in body onload

AphX
AphX used Ask the Experts™
on
Hi!

I'm using this code snippet.

http://www.tek-tips.com/faqs.cfm?fid=5889

The function only works when I run it with body onload.

If I declare an own function inside there I'm able to run it like this:

<script type="text/javascript" language="javascript">
    aFunction();
</script>

But the drawGradient(); function or createGradientV(); function etc only runs from body onload... Why is that? / How can I make it run like the example above?

Please try the code snippet from the link above.

Thanks!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you can run it like this:

<script type="text/javascript" language="javascript">
    drawGradient();
</script>

as long as you let the the page completely load, i.e., if you add this to the end of the page. The gradient function uses the divs created inside the body, so it won't work if you don't let them be created first.
The function uses fadeBandsV and fadeBandsH as canvases. Therefore, it needs the page to be loaded so these elements are available to use. Or the calls must be made below the elements. You cannot place the function call in the head section. See example:
<head>
<script type="text/javascript" language="javascript">
    function aFunction() {
        drawGradient();
    }
</script>
</head>
<body>
    <div id="fadeBandsV"></div>
    <div id="fadeBandsH"></div>
 
<script type="text/javascript" language="javascript">
    aFunction(); // you may call it from this point downwards
</script>
 
    <div id="pageContent">
        <h1>A test heading</h1>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras lorem. Proin laoreet fringilla sem. Pellentesque malesuada, urna tristique ornare feugiat, turpis wisi ultrices nisl, ac vulputate dolor justo non sapien. Sed fermentum velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam at nulla. Maecenas tortor nulla, adipiscing eget, auctor sed, cursus id, quam. Suspendisse at sem nonummy orci lobortis ultrices. Proin odio est, dictum id, dictum nec, ullamcorper sit amet, sem. Proin ullamcorper lacus vitae risus. Nulla feugiat posuere erat. In nec est ac eros lacinia congue. Suspendisse potenti. In a ipsum rhoncus ipsum volutpat consectetuer.</p>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras lorem. Proin laoreet fringilla sem. Pellentesque malesuada, urna tristique ornare feugiat, turpis wisi ultrices nisl, ac vulputate dolor justo non sapien. Sed fermentum velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam at nulla. Maecenas tortor nulla, adipiscing eget, auctor sed, cursus id, quam. Suspendisse at sem nonummy orci lobortis ultrices. Proin odio est, dictum id, dictum nec, ullamcorper sit amet, sem. Proin ullamcorper lacus vitae risus. Nulla feugiat posuere erat. In nec est ac eros lacinia congue. Suspendisse potenti. In a ipsum rhoncus ipsum volutpat consectetuer.</p>
    </div>
</body>

Open in new window

Author

Commented:
Great answers!

Thank you guys!

Commented:
It only runs onload because it actually manipulates element styles for entities that need to be fully loaded and rendered before they can be changed.

You can get around this a couple of ways. Most browsers will be fine if you move your drawGradient(); into a script tag right above the closing body tag like twocandles just stated.
<html>
...
<body>
   .... Divs and such go here
  <script type="text/javascript" language="javascript">
     drawGradient();
  </script>
</body>
</html>

If you are worried, you can even add a delay to the function firing, to ensure the elements have all rendered.

setTimeout("drawGradient();",1000);


HonorGodSoftware Engineer

Commented:
I'm sorry, I don't understand.

When I tried using the code unchanged, I saw what it was supposed to do, then I changed it to this, to add a button to call "drawGradient()".

This seemed to work just fine.

What browser are you using?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="content-language" content="en" />
    <title>Gradient Background</title>
 
    <style type="text/css">
        body {
            padding: 0px;
            margin: 20px;
            background-color: #00CCFF;
        }
 
        #fadeBandsV {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 80px;
            z-index: 1;
        }
 
        #fadeBandsH {
            position: absolute;
            left: 0px;
            top: 0px;
            width: 100%;
            z-index: 1;
        }
 
        #fadeBandsV div {
            overflow: hidden;
            position: absolute;
            width: 100%;
        }
 
        #fadeBandsH div {
            overflow: hidden;
            position: absolute;
            height: 200px;
        }
 
        #pageContent {
            position: relative;
            z-index: 2;
        }
    </style>
 
    <script type="text/javascript">
    <!--
 
        // do not call this function directly - use createGradientV or createGradientH instead
        function createGradient(direction, args) {
            var bandSets = args.length / 4;
            var startPos = 0;
 
            for (var bandSetLoop=0; bandSetLoop<bandSets; bandSetLoop++) {
                fadeFromColour = args[bandSetLoop * 4];
                fadeToColour = args[bandSetLoop * 4 + 1];
                bandSize = args[bandSetLoop * 4 + 2];
                fadeSteps = args[bandSetLoop * 4 + 3];
 
                // calculate stepped colour values for each band
                var colourSteps = [fadeFromColour.concat()];                // ensure first colour is the start colour
                for (var bandLoop=1; bandLoop<fadeSteps; bandLoop++) {
                    colourSteps[bandLoop] = [];
                    for (var rgbLoop=0; rgbLoop<3; rgbLoop++) {
                        colourSteps[bandLoop][rgbLoop] = Math.round(colourSteps[bandLoop-1][rgbLoop] + ((fadeToColour[rgbLoop] - colourSteps[bandLoop-1][rgbLoop]) / (fadeSteps - bandLoop)));
                    }
                }
 
                // now draw each band
                if (direction == 'V') {
                    for (var bandLoop=0; bandLoop<fadeSteps; bandLoop++) {
                        document.getElementById('fadeBandsV').appendChild(aDiv = document.createElement('div'));
                        aDiv.style.height = bandSize + 'px';
                        aDiv.style.top = startPos + (bandSize * bandLoop) + 'px';
                        aDiv.style.backgroundColor = 'rgb(' + colourSteps[bandLoop][0] + ',' + colourSteps[bandLoop][1] + ',' + colourSteps[bandLoop][2] + ')';
                    }
                } else {
                    for (var bandLoop=0; bandLoop<fadeSteps; bandLoop++) {
                        document.getElementById('fadeBandsH').appendChild(aDiv = document.createElement('div'));
                        aDiv.style.width = bandSize + 'px';
                        aDiv.style.left = startPos + (bandSize * bandLoop) + 'px';
                        aDiv.style.backgroundColor = 'rgb(' + colourSteps[bandLoop][0] + ',' + colourSteps[bandLoop][1] + ',' + colourSteps[bandLoop][2] + ')';
                    }
                }
                startPos += fadeSteps * bandSize;
            }
        }
 
        // createGradientV - creates a vertical gradient (North to South)
        // Parameters: createGradientV takes a single set, or multiple sets of, 4 arguments:
        //         argument 1: fadeFromColour = an array of R,G,B colours to fade from (for example, [0, 0, 255] == #0000FF)
        //         argument 2: fadeToColour = an array of R,G,B colours to fade to (for example, [0, 204, 255] == #00CCFF)
        //         argument 3: bandHeight = height of each colour band
        //         argument 4: fadeSteps = number of colour bands used for the gradient (should be at least 2)
        function createGradientV() {
            if (arguments.length < 1 || arguments.length % 4 != 0) {
                alert('Incorrect usage. Number of parameters must be a multiple of 4!');
                return;
            }
            createGradient('V', arguments);
        }
 
        // createGradientH - creates a horizontal gradient (West to East)
        // Parameters: createGradientH takes a single set, or multiple sets of, 4 arguments:
        //         argument 1: fadeFromColour = an array of R,G,B colours to fade from (for example, [0, 0, 255] == #0000FF)
        //         argument 2: fadeToColour = an array of R,G,B colours to fade to (for example, [0, 204, 255] == #00CCFF)
        //         argument 3: bandHeight = height of each colour band
        //         argument 4: fadeSteps = number of colour bands used for the gradient (should be at least 2)
        function createGradientH() {
            if (arguments.length < 1 || arguments.length % 4 != 0) {
                alert('Incorrect usage. Number of parameters must be a multiple of 4!');
                return;
            }
            createGradient('H', arguments);
        }
 
        function drawGradient() {
            createGradientV([255, 0, 0], [255, 255, 0], 3, 50, [255, 255, 0], [0, 0, 255], 3, 50, [0, 0, 255], [0, 204, 255], 3, 50);
            createGradientH([255, 0, 0], [255, 255, 255], 3, 50, [255, 255, 255], [0, 0, 255], 3, 50);
        }
 
    //-->
    </script>
</head>
 
<body>
    <div id="fadeBandsV"></div>
    <div id="fadeBandsH"></div>
    <div id="pageContent">
        <h1>A test heading</h1>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras lorem. Proin laoreet fringilla sem. Pellentesque malesuada, urna tristique ornare feugiat, turpis wisi ultrices nisl, ac vulputate dolor justo non sapien. Sed fermentum velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam at nulla. Maecenas tortor nulla, adipiscing eget, auctor sed, cursus id, quam. Suspendisse at sem nonummy orci lobortis ultrices. Proin odio est, dictum id, dictum nec, ullamcorper sit amet, sem. Proin ullamcorper lacus vitae risus. Nulla feugiat posuere erat. In nec est ac eros lacinia congue. Suspendisse potenti. In a ipsum rhoncus ipsum volutpat consectetuer.</p>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras lorem. Proin laoreet fringilla sem. Pellentesque malesuada, urna tristique ornare feugiat, turpis wisi ultrices nisl, ac vulputate dolor justo non sapien. Sed fermentum velit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam at nulla. Maecenas tortor nulla, adipiscing eget, auctor sed, cursus id, quam. Suspendisse at sem nonummy orci lobortis ultrices. Proin odio est, dictum id, dictum nec, ullamcorper sit amet, sem. Proin ullamcorper lacus vitae risus. Nulla feugiat posuere erat. In nec est ac eros lacinia congue. Suspendisse potenti. In a ipsum rhoncus ipsum volutpat consectetuer.</p>
    </div>
    <input type='button' value='Gradient' onclick='drawGradient();'>
</body>
</html>

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial