Forum Moderators: open

Message Too Old, No Replies

How to convert a script that uses window.onload to load automatically?

         

John_Creed

5:14 pm on Oct 15, 2009 (gmt 0)

10+ Year Member



Below is an example of my CURRENT script that uses windows.onload. How do I modify this so that the javascript loads as soon as the links load and not after the entire webpage is done loading?

<div id="myDiv">
<a href="http://www.google.com">Google</a>&nbsp;<a href="http://www.yahoo.com">Yahoo</a>&nbsp;<a href="http://www.live.com">Live</a>
<a href="http://www.google.com">Google</a>&nbsp;<a href="http://www.yahoo.com">Yahoo</a>&nbsp;<a href="http://www.live.com">Live</a>
<a href="http://www.google.com">Google</a>&nbsp;<a href="http://www.yahoo.com">Yahoo</a>&nbsp;<a href="http://www.live.com">Live</a>
</div>
<script type="text/javascript">
window.onload = function() {
var whatColor, whatSize;
var myColors = ["Red","Green","Blue","Pink","Yellow","Purple","Orange"];
var fontMin = 10;
var fontMax = 40;
var div1 = document.getElementById("myDiv");
var links = div1.getElementsByTagName("a")
for(i=0;i<links.length;i++) {
whatColor = Math.floor(Math.random() * myColors.length);
whatSize = Math.floor(Math.random() * (fontMax - fontMin + 1)) + fontMin;
links[i].style.color = myColors[whatColor];
links[i].style.fontSize = whatSize + "px";
}
}
</script>

penders

5:38 pm on Oct 15, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



<div id="myDiv"> 
:
</div>
<script type="text/javascript">
function styleLinks() {
// Rest of function
:
:
}
styleLinks(); // Call the function
</script>

Providing the function is called after your links in the document, it should be OK. To keep your page less cluttered, you could put your JavaScript before your closing BODY tag - after all your markup.

John_Creed

5:55 pm on Oct 15, 2009 (gmt 0)

10+ Year Member



Thank you! It appears to work perfectly.