Working with IFRAME in JavaScript – How to write content dynamically into IFRAME using JavaScript: discussion

Within the code in the previous section, I mainly created a simple text box and a button.  The textbox is named “txtContent” and the button is named  “ButtonShowMsg.”  The button is defined with an “onclick” event which calls a JavaScript function “ButtonShowMsg_onclick,” which is defined as follows:

function ButtonShowMsg_onclick() {
var v = document.all(“txtContent”).value;
Show(v);
}

The above function defines a variable “v”, which is assigned with a value available (or typed) in the textbox “txtContent.”  The same variable is passed as a parameter to another JavaScript function, “Show.”

The function “Show” is defined as follows:

function Show(val)
{
var testFrame = document.getElementById(“myFrame”);
var doc = testFrame.contentDocument;
if (doc == undefined || doc == null)
doc = testFrame.contentWindow.document;
doc.open();
doc.write(val);
doc.close();

document.all.myFrame.style.visibility=”visible”;
}

Let me explain the above function part by part.  Let us first consider the following statement.

var testFrame = document.getElementById(“myFrame”);

The above statement tries to retrieve the handle of the IFRAME, which is declared in our web page with the ID “myFrame.”  Further proceeding we have the following:

var doc = testFrame.contentDocument;
if (doc == undefined || doc == null)
doc = testFrame.contentWindow.document;

To write some content to the IFRAME, we need to get the handle of the “document” object of the specific IFRAME.  This is achieved through the above statements.  The “if” statement is a simple “hack” to make it work with different browsers.  Further proceeding, we have the following:

doc.open();
doc.write(val);
doc.close();

Once we get the handle of the “document” object of the respective IFRAME, we need to open it, write the content and close it.  All three above do the same.


One Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.