getImgAreas.js

function getImgAreas( ) { var result; // make sure browser supports img element objects if (document.images) { // initialize return value so we can add to it result = 0; // loop through all img objects on the page for (var i = 0; i < document.images.length; i++) { // accumulate image areas result += (document.images[i].width * document.images[i].height); } } // returned value is either a number or null return result; } function reportImageArea( ) { // grab result so we can verify it var imgArea = getImgAreas( ); var output; if (imgArea == null) { // message for browsers not supporting img object output = "Unknown"; } else { output = imgArea; } document.reportForm.imgData.value = output; }
A smarter scripter would recognize that the preceding scripts might fail in very old browsers, where script errors tend to be rather invasive. To prevent such errors, the author makes two modifications. First, the potentially offending script statements in the getImgAreas( ) function wrap themselves in an object detection block. Second, the main function intelligently accommodates the possibility that the getImgAreas( ) function won’t be doing any calculations at all.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.