SteveMurphy Posted July 18, 2009 Share Posted July 18, 2009 I'm learning javascript and I have IE 6.0.Following is a complete html page that I'm using. including Javascript to write window dimensions to a div element in the HTML body. You'll notice that I'm using window.onresize to identify the callback.I have two problems:1) The onresize callback is called three times each tme I resize the window.2) The code to write the dimensions seem to work the first time I resize the window, but not thesecond and subsequent times.I'm a beginner so my code is very amateurish. In addition to helping solve the immediate problems, any feedback you have for me is welcome.ThanksSteve <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"><html xmlns="http://www.w3.org/1999/xhtml"><head> <style type="text/css"> h1, h2, h3, body {font-family: arial} body {font-size: 80%} </style> <title>onResize Sample</title> <script language="Javascript" type="text/javascript"> <!-- Hide code from older browsers // The div where dimensions are displayed var divNode; var oldTextNode; window.onresize=showDimensions function showDimensions() { try { var newTextNode = document.createTextNode("Dimensions: " + document.body.offsetWidth + "(w) x " + document.body.offsetHeight + " (h)"); divNode.replaceChild(newTextNode, oldTextNode); } catch(err) { showError(err, "showDimensions"); } } function showError(e, func) { alert("Error in " + func + "\n" + e.description); } // Stop hiding code --> </script></head><body bgcolor="#FFFFFF"> <h1> Window Dimensions </h1> <div id="dimensions"> a </div></body><script language="Javascript" type="text/javascript"> <!-- Hide code from older browsers //Get a reference to the dimensionsArea div try { divNode = document.getElementsByTagName("div").item(0); oldTextNode = divNode.firstChild; //showDimensions(); } catch(err) { showError(err, "script below body element"); } // Stop hiding code --> </script></html> Link to comment Share on other sites More sharing options...
justsomeguy Posted July 20, 2009 Share Posted July 20, 2009 You need to save the text node as oldTextNode so that it gets overwritten the next time through the function. var newTextNode = document.createTextNode("Dimensions: " + document.body.offsetWidth + "(w) x " + document.body.offsetHeight + " (h)"); divNode.replaceChild(newTextNode, oldTextNode); oldTextNode = newTextNode; I added the last line. You can't really control how the browser fires the resize event, so if you need the function to only run once you can keep track of the last time it ran and only run it again if it's been a certain amount of time. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.