Writing Dynamic Content with JavaScript

write form field text to layer

write, "<p>Any HTML can go here</p> <img src=jennifer.png>"

Writing content to layers is fairly straight forward, the usual browser differences aside. This is one of the most practical uses of DHTML - changing page content on the fly without having to reload or overwrite the page.

With Netscape 4.x, the code should look familiar:

**NOTE: this script requires the browser sniffing script from the previous section in order to function properly.
Where content is a string variable representing HTML or plain text.

Internet Explorer 5+, Netscape 6+ and all standards compliant browsers write to layers using the innerHTML property:
document.getElementById('layerName').innerHTML = content
Internet Explorer 4 and 4.5 varying slightly with its document.all syntax:
document.all['layerName'].innerHTML = content
Notice that innerHTML is not a property of the style object.

To create the effect in this example, the layers are hidden until the mouse moves over the links. Here is the entire function:
function writeContent(id,text) {
var layer = browser(id)  //get path to layer using global browser function

var content
content = "<table border=0 bgcolor=\"#000000\">"+
"<tr><td width=\"100%\">"+
"<table border=0 width=\"100%\" bgcolor=\"#ffcc33\">"+
"<tr><td width=\"100%\">" + text + "</td></tr>"+ //arg 'text' used here

	if(nn4) {	
	layer.document.write(content) //write content to layer
	layer.visibility="visible"	//change visibility to visible
	else {		     
	layer.innerHTML = content  //write content to layer
	layer.style.visibility="visible"	//change visibility to visible
When the function is invoked, an argument is passed that is used as the dynamic content. The first link passes the value of the form field as the argument. In the second link, the argument is a literal string.
<a href="..." onMouseOver="writeContent('blockDiv1',document.layerForm.layerText.value)">...</a>

<span ID="blockDiv1"></span>

<a href="..." onMouseOver="writeContent('blockDiv2','<p>Any HTML can go here</p><img src=laugh.gif>')">...</a>
<span ID="blockDiv2"></span>
The hideLayer() function which is called onMouseOut is short and sweet, it simply changes the layer's visibility back to hidden.
function hideLayer(id) {
var layer = browser(id)	

<a href="..." onMouseOver="..." onMouseOut="hideLayer('blockDiv1')">...</a>

<a href="..." onMouseOver="..." onMouseOut="hideLayer('blockDiv2')">...</a>
To simplify this example, the style rules for the empty layers set the position to absolute, without specifying top and left values.
#blockDiv1{ position:absolute; visibility:hidden }
This is done to keep from having to write complex positioning code for relative positioning, while still achieving a relative positioning effect. This is not a fool-proof workaround however, as different browsers will still position the layers slightly differently (what's new, eh?).

View Source | Home | Contact