Categories:
Partners

Dynamic Content in Firefox

There are two ways to implement dynamic content in Firefox:

1) Through the W3C deprecated .innerHTML property (same as IE)
2) Through the standards compliant DOM methods of W3C

-Method 1

Firefox supports the primary property IE uses for dynamic content, which is .innerHTML. While this property is non standards compliant, Firefox supports it due to its ease of use and implementation:

<div id="test">Old content</div>

<script>
//below code should be called after page has loaded
document.getElementById("test").innerHTML="new content"
</script>

-Method 2

Using purely DOM methods as proposed by W3C to simulate .innerHTML is a little more tricky, and for the extra work involved, may not be practical. Nevertheless, the following elegant code is devised by Rey Nunez, a surfer of JavaScript Kit and active helper on CodingForums. Using the below function, we can accomplish dynamic content in Firefox using pure DOM methods:

function dynamiccontentNS6(elementid,content){
if (document.getElementById && !document.all){
rng = document.createRange();
el = document.getElementById(elementid);
rng.setStartBefore(el);
htmlFrag = rng.createContextualFragment(content);
while (el.hasChildNodes())
el.removeChild(el.lastChild);
el.appendChild(htmlFrag);
}
}

I won't go into detail as to how the function is constructed. Basically, document.createRange() is first used to set up a "range" over the entire document. removeChild() is then used to clear the contents of the specified element, and replaced with the new content, through appendChild(). The following demonstrates using this function to create on-the-fly HTML descriptions. Move your mouse over the links on the left:

What's New?

-In Free JavaScripts
-In JavaScript tutorials
-In Web Tutorials

The source code for each link look like this:

<a href="#" onMouseover=
"dynamiccontentNS6('thetext',linkcontent[0])">In Free JavaScripts</a>

Where linkcontent[0] is an arbitrary variable that holds the actual HTML for the first link's description.

For the right table column that displays the HTML description, a <span> with id "thetext" is used:

<span id="thetext" style="width:100%"></span>

That's all there is to it (along with Rey's function, of course).