Creating Dynamic HTML in Internet Explorer 4+ using JavaScript

This excerpt is from Chapter 12 ("Dynamic HTML") of Paul Wilton's book, Beginning JavaScript. It outlines how you can access the tags in an HTML page to change them dynamically and enhance user interaction. It describes a couple of simple (but fun) examples of creating dynamic content in HTML pages using JavaScript for use on Microsoft's Internet Explorer browser, version 4.0 and later. Each of the examples has a full code listing, and an explanation of how it works. To use an example, you can simply type it into a text editor, save it as an .htm file, and then load it up into Internet Explorer.

Share:

Paul Wilton, Author, Beginning Javascript

After an initial start as a Visual Basic applications programmer at the Ministry of Defense in the UK, Paul Wilton found himself pulled into the Net. Having joined an Internet development company, he spent the last three years helping create Internet solutions and is currently working on an e-commerce Web site for a major British bank. Paul's main skills are in developing Web front ends using DHTML, JavaScript, VBScript, and Visual Basic, and back-end solutions with ASP, Visual Basic, and SQL Server. Currently, he's expanding his skill set to include ADSI programming of Windows 2000 Active Directory.



01 April 2001

Also available in Japanese

Excerpt from the Wrox Title Beginning JavaScript


Dynamic HTML in Internet Explorer 4.0+

[In] Internet Explorer, most tags, even simple tags like the <P> tag, are represented by objects. The attributes of these tags are often represented as properties of the objects. The objects also have an amazing number of other properties, as well as methods and events, probably totaling almost a hundred. Some of these properties are themselves objects with even more properties and methods.

In this section we'll be looking at just the fundamentals of DHTML with IE. With the fundamentals under your belt you can explore further the properties, methods and events IE makes available by looking at Appendices E and F of Beginning JavaScript for IE BOM references, or referring to the advanced DHTML books available from Wrox Press (see Resources).

Accessing page tags

How do you access the objects of HTML tags, to change their properties, call their methods and hook into their events? We obviously need some way of specifying which individual tag you are referring to. So far in this book we have been giving tags a Name attribute and using this to access them. For example, a text box within a form could be defined like this:

Listing 1a
    <FORM
name="myForm">
       <INPUT TYPE="text" name="text1">
    </FORM>

We then refer to the corresponding Form object in JavaScript using the form's name, myForm, and the text box's Text object using the name, text1:

Listing 1b
    document.myForm.text1.value

In IE's DHTML, however, we use a different way of uniquely identifying tags, namely with a tag's ID attribute. This works in a very similar way to the NAME attribute. Certain elements, such as forms and controls on forms, still require the NAME attribute, as it's this that's passed to a server if the form is posted. However, for most other elements, we can just use the ID attribute.

For example, if we have a paragraph tag, <P>, which we want to access via script, we write:

Listing 1c
    <P ID="myPara">A Paragraph</P>

To access this in our JavaScript code we simply use the ID value. For example, if we wanted to retrieve the text inside the paragraph, we would use the P object's innerText property with the code:

Listing 1d
myPara.innerText;

which will be "A Paragraph" in this example. I'll talk about the innerText property in more detail later in this chapter.

Another way of accessing the objects associated with tags is the document objects all array property (or, more precisely, collection property). This property contains all the elements defined in the source code for the page in source code order. We can reference an element by either using its index in the array, or its ID value in square brackets after the all word. For example, to reference the above paragraph we could use:

Listing 1e
document.all["myPara"];

However, for our purposes in this chapter, it is easier to use the former way of referencing tags' objects.


Changing appearances

The key to changing the look of an HTML tag once the page has been loaded is the style object, which almost every tag's object has as a property. The style object is JavaScript's representation of a tag's style sheet, which we saw earlier, and most properties we can set with style sheets can also be set using the style object. In Appendices E and F you'll find a guide to the properties of the style object.

One example of a property of the style object is color. Quite obviously, this can be used to change the color of an object. For example, to change the color property of the style object property of a paragraph with ID of myPara, we would use:

Listing 1f
myPara.style.color='red';

This technique of using the style object property of the object representing a particular tag to change the tag's appearance works for most tags, with a wide range of appearance changes being available. Everything, from background color to text spacing, text size and even whether the tag is visible to the user, can be determined using the style object.

Try it out -- using the style object

Let's have a go at a simple example using the style object.See listing 2.

Listing 2
    <HTML>

    <HEAD>

    <SCRIPT LANGUAGE=JavaScript>
    function myPara_onmouseout() 

    {

       myPara.innerText = "Roll your mouse over my text";

       myPara.style.color = "Black"

    }
    function myPara_onmouseover() 

    {

       myPara.innerText = "Wow that feels good!!!";

       myPara.style.color = "Red"

    }
    </SCRIPT>

    </HEAD>
    <BODY>

    <P ID="myPara" 

       onmouseout="return myPara_onmouseout()" 

       onmouseover="return myPara_onmouseover()">

          Roll your mouse over my text

    </P>

    </BODY>

    </HTML>

Save this as rollover_IE.htm. Load it into your browser, and you should see a paragraph with the text "Roll your mouse over my text." (see Figure 1).

Figure 1: Paragraph with text
Figure 1: Paragraph with text

On doing this, the color of the text changes to red, and the text message changes to "Wow that feels good!!!" (see Figure 2).

Figure 2: Text color red
Figure 2: Text color red

On moving your mouse off of the text, the text returns to the original color and message.

How it works

In the body of the page, we define a paragraph with ID of myPara. We connect the onmouseout event handler for this paragraph to the function myPara_onmouseout() and the onmouseover event handler to the function myPara_onmouseover(). These functions are defined in a script block in the head of the page.

The myPara_onmouseover() function, which is called when the user's mouse rolls over the paragraph, starts by changing the text of the paragraph. It does this using the innerText property that we saw above. See listing 3a.

Listing 3a
    function
myPara_onmouseover() 

    {

       myPara.innerText = "Wow that feels good!!!";

Then, the function uses the color property of the style object property of the myPara object to change the color of the paragraph. See listing 3b.

Listing 3b
myPara.style.color = "Red"

    }

The myPara_onmouseout() function, which is called when the user's mouse rolls off the paragraph, has very similar functionality. It simply changes the text back to its original value, and changes the color property of the style object back to black.


Positioning and moving content

We saw earlier how we can use style sheets to determine the exact position of HTML elements on a page when it's loaded. Well, using JavaScript we can move these absolutely or relatively positioned elements around after the page has loaded, again using the style object. In this case we can use the style object's left and top properties to change the left and top positions of HTML elements.

Try it out -- moving text

Let's see an example of how to use JavaScript to move the content around after it has loaded. In this case, we're going to make two paragraphs scroll from left to right, then back again in a continuous loop. we'll use timer functionality to keep the tags moving. See listing 4a.

Listing 4a
    <HTML>

    <HEAD>

    <SCRIPT LANGUAGE=JavaScript>
    var paraOneLeft = 100;

    var paraTwoLeft = 400;

    var switchDirection = false;
    function window_onload() 

    {

       window.setInterval("moveParas()",50);

    }
    function moveParas()

    {

       if (switchDirection == false)

       {

          paraOneLeft++;

          paraTwoLeft--;
          if (paraOneLeft == 400)

          {

             switchDirection = true;

          }

       }

       else

       {

          paraOneLeft--;

          paraTwoLeft++;
          if (paraOneLeft == 100)

          {

             switchDirection = false;

          }

       }
       para1.style.left = paraOneLeft + "px";

       para2.style.left = paraTwoLeft + "px";

    }
    </SCRIPT>

    </HEAD>
    <BODY LANGUAGE=JavaScript onload="window_onload()">
    <P STYLE="position:relative;left:100px;top:30px" ID="para1">Para 1</P>

    <P STYLE="position:relative;left:400px;top:10px" ID="para2">Para 2</P>
    </BODY>

    </HTML>

Save the page as MovingTags_IE.htm and load it into your Internet Explorer 4.0+ browser. Hopefully, the contents of the two tags (Para 1 and Para 2) will scroll smoothly across the screen in opposite directions and back again continuously.

How it works

In the body of the page we have two <P> elements. Each has been given a unique ID value (para1 and para2) and it's this that we will use to reference the P object associated with each tag.See listing 4b.

Listing 4b
    <P STYLE="position:relative;left:100px;top:30px" ID="para1">Para 1</P>

    <P STYLE="position:relative;left:400px;top:10px" ID="para2">Para 2</P>

Within the STYLE attribute, you have positioned the paragraphs at the co-ordinates 100,30 and 400,10. Note that this means that para2 will be above para1.

Note that we've positioned the paragraphs relatively rather than absolutely, even though the two <P> tags are not inside other tags. Why?

Well, this is for browser compatibility. IE 4 does not support the absolute positioning of <P> tags but it does support relative positioning of them. IE 5.0+ supports both absolute and relative positioning for <P> tags, so we would have no problems. In this example, using relative positioning when not inside another tag gives the same effect as absolute positioning.

An alternative would be to use the <DIV> tag which is a container tag, that is it does not display anything, but allows you to group tags together inside it. This supports absolute and relative positioning in IE 4 and IE 5, so you could have put each paragraph inside a separate absolutely positioned <DIV> tag and moved the <DIV> tag about instead.

Within the script block in the head of the page, after we've declared three variables that will be used to determine the left positions and the scroll direction of the paragraphs, we then come to the window_onload() function. See listing 4c.

Listing 4c
    function window_onload() 

    {

       window.setInterval("moveParas()",50);

    }

Here we start a timer going using the setInterval() method of the window object, which will call the moveParas() function every 50 milliseconds. The definition of the moveParas() function comes next in the script block. This function is used to actually move the paragraph's text.

How do we want the paragraph's text moved?

We want the top paragraph, para2, to start with a left position of 400, then move by one-pixel decrements to the left until the left position is 100. At that point we want to switch directions and start moving the paragraph back to a left position of 400 by increasing the left position by one pixel until it's 400, whereupon we switch directions again and the process starts again.

We want the bottom paragraph, para1, to do the exact opposite of the top paragraph: We want it to start at a left position of 100, then scroll to the right by one pixel until it hits a left position of 400, then switch direction and scroll back until it has a left position of 100 again.

To achieve this, the first task of the moveParas() function is to determine which way to scroll the paragraphs. It does this by using the switchDirection variable, which will have the value false if para1 is scrolling right, and the value true if para1 is scrolling left. It was initialized to false at the top of the script block.

In the first if statement, the condition checks whether switchDirection has value false. If so, it increments the left position of para1 by 1 and decrements the left position of para2 by one. It then checks in an inner if statement whether the left position of para1 is 400. If so, then it is time to switch the direction of the scrolling, so it sets the value of the variable switchDirection to true.See listing 4d.

Listing 4d
    function moveParas()

    {

       if (switchDirection == false)

       {

          paraOneLeft++;

          paraTwoLeft--;
          if (paraOneLeft == 400)

          {

             switchDirection = true;

          }

       }

Next, in an else statement, we have similar code for the situation where switchDirection is true, that is the scrolling is in the opposite direction.See listing 4e.

Listing 4e
else

       {

          paraOneLeft--;

          paraTwoLeft++;
          if (paraOneLeft == 100)

       {

             switchDirection = false;

       }

    }

Finally, we set the left position of the paragraphs in exactly the same way we set the color in our previous example: by using each P object's style object property.See listing 4f.

Listing 4f
para1.style.left = paraOneLeft + "px";

       para2.style.left = paraTwoLeft + "px";

    }

That completes the moveParas() function, and the script block.

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=11525
ArticleTitle=Creating Dynamic HTML in Internet Explorer 4+ using JavaScript
publish-date=04012001