Refresh Style Sheets (layouts) with JavaScript
Added: February 13th, 2007 (tagged with: coding, javascript)
The other day, I was building a web site for one of the departments at work. The site has a fixed layout that aligned to the center of the page (body { width: 760px; margin: 0px auto; } and a few absolutely positioned elements. The problem with this configuration is that when a browser window is resized, the positions of those few elements did not change.
My first thought was to dynamically (through JavaScript) refresh the page on a resize event (window.location.reload();). That doesn't work because the entire page is fetched each time the reload is called. The content doesn't change, why should the user be forced to round-trip with the server each time the resize (or drag) the window?
Then I remembered the customization code I have on my web site that allows style sheet changes on the fly with JavaScript. A quick little change and I adapted the code for my new needs:
var i, a;
for( i = 0; ( a = document.getElementsByTagName("link")[i] ); i++ )
{
if( a.getAttribute("rel").indexOf("style") != -1 )
{
a.disabled = true;
a.disabled = false;
}
}
The block of JavaScript above loops through all of the link elements in a document, and for each style sheet it finds, it disables and re-enables the style. This happens so quickly that users don't notice it happen. It has the effect of refreshing just the style sheet and not the entire page, all without a round-trip to the server.
Updated: April 23rd, 2007
CSS-based solution to my original problems: How to Center a Fixed Layout Page with CSS
