0
votes

i have the following code, that randomizes text from an array.

However what im not sure how to do the following.

  1. display the result on browser load instead of onclick.
  2. display the output to a div CLASS on load (so if i have multiple divs called "output", a random font/size/weight will be displayed in each div)
  3. it should take the font from each div element and change the classes etc, instead of using the font names etc.
  4. instead of using the font names in an array, how do i point each variable to a class? .font1 {font-family:Verdana, Geneva, sans-serif;} .font2 {font-family:Georgia, "Times New Roman", Times, serif;} .font3 {font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;} .font4 {font-family:"Times New Roman", Times, serif;} .font5 {font-family:"Comic Sans MS", cursive;} var fonts = ['.font1', '.font2', '.font3', '.font4', '.font5'];

really hope someone can help.

code is as follows;

<button onclick="run()">Test</button>
<div id="output"/>

var fonts = ['Arial', 'Helvetica', 'Georgia', 'Tahoma', 'Verdana'];
var weights = ['normal', 'bold', 'lighter'];
var sizes = ['16px', '20px', '24px', '36px', '40px'];

var choose = function(arr) {
return arr[Math.floor(Math.random() * arr.length)];
};
var output = document.getElementById("output");

window.run = function() {
var text = choose(sizes) + ' ' + choose(weights) + ' '  +  choose(fonts);
output.innerHTML = '<div class="randomFont" style="font: ' + text + '">' + text +      '</div>';
}
2

2 Answers

1
votes
  1. You can attach an event listener to the window load event:

    window.addEventListener('load', run, false);
    

    Better yet, if the browsers you're targeting support it, you could use DOMContentLoaded, which will not wait for images, stylesheets, and other less-essential resources to load:

    document.addEventListener('DOMContentLoaded', run, false);
    

    You could even use a combination of the two: attach to both, and in run, only do it when it has not already been done.

  2. You can find all of the elements with a given class using document.getElementsByClassName. You can then iterate over the returned collection and give a random font to each of those.

  3. (and 4.) Rather than constructing some HTML and a CSS string, you could instead use the style property for the weights and sizes. For example:

    element.style.fontWeight = 'bold';
    

    For the font family, select one of your classes and append a space and then it to the element's className property:

    element.className += ' ' + fontFamilyClass;
    

Try it out.

0
votes

You are building the style as a shorthand, but the order you specify them in is wrong the size should be before the family. The proper way would be <div style=bold 16px Verdana></div>

Here is a working example:

http://jsfiddle.net/7egCK/2/

If you would like this to happen on load simply execute your html render function in onLoad event of the Body

<body onLoad="run()">