Drawing with Stylesheets and Javascript4. Javascript Generated |
|
Join the DiscussionMore of this FeatureTo generate the HTML for our drawing we still need all of the stylesheet commands that we already created. That part doesn'r change. What you will have noticed if you started trying to construct the HTML for the drawing is that it just consists of lots of empty div tags that only differ in what classes are attached to them. This makes generating the HTML for the drawing from Javascript really easy. Here's the first part of our Javascript code.
var divo = '<div class="';
var divc = '"><\/div>'; var topArray = ['wt w14 l','bl','wt w12','bl','wt w14', 'wt w14 l','bl','wt w12','bl','wt w12','bl','wt w14','wt w14 l','bl', 'wt w12','bl','wt w14','wt w14 l','bl','wt w12','bl','wt w12','bl', 'wt w14','wt w14 l','bl','wt w12','bl','wt w14','wt w14 l','bl', 'wt w12','bl','wt w12','bl','wt w14','r1']; var bottomArray = ['wb w20','','wb w23','','wb w19', 'wb w20','','wb w23','','wb w23','','wb w19','wb w20','', 'wb w23','','wb w19','wb w20','','wb w23','','wb w23','', 'wb w19','wb w20','','wb w23','','wb w19','wb w20','', 'wb w23','','wb w23','','wb w19','r2']; So what we have now defined are two fields that contain the fixed part of each div and two arrays that contain the lists of the classes to use for each of the parts of our drawing. To make it easier to relate the top and bottom pieces of our white keys we have added empty entries in the second array so that the top and bottom pieces are in the same position in each array. Now we can construct the entire drawing into a single Javascript field using the following code:
var draw = '<div
class="clear">';
var len = topArray.length; for (var i = 0; i < len; i++) { draw += divo + topArray[i] + divc;} draw += '<\/div><div class="clear">'; for (var i = 0; i < len; i++) { if (bottomArray[i] != '') draw += divo + bottomArray[i] + divc;} draw += '<\/div><div class="clear"><\/div>'; This Javascript code simply loops through each of the two arrays in turn building all of the div tags that we need for us. We can then simply attach the entire drawing into the page either using document.write(draw); in a javascript in the body of our page or by using document.getElementById('diagram').innerHTML = draw; to insert it into a predefined place in the page after the page finishes loading. The final step is to add the extra Javascript to animate our drawing. |

