devxlogo

Twelve Dynamic HTML Lessons

Twelve Dynamic HTML Lessons

ascading Style Sheets are a necessary ingredient for, and one of the key components of, DHTML. They’re also a good idea for managing Web pages in general.

Cascading Style Sheets, or CSS for short, is an approach that has been evolving for quite some time. It was first supported in IE 3.0 and, like many of you, we started reading the available information about style sheets when IE3.0 was released. We got confused. The specs weren’t helpful. The online documentation we found couldn’t demystify it for us. We stopped in confusion and said we’d learn it later because there was so much else to do now.

Well, “Later” has become today and we’ve discovered that CSS isn’t as hard as it appeared at first glance. In fact, we’re going to explain it to you in very short order and you too will understand it. Even if you don’t fully understand it, you’ll have enough working knowledge that you can use it to your advantage.

Before you begin using CSS though, there are a couple of guidelines you should know:

  • CSS is very finicky about syntax. One misspelling, one misplaced semi-colon and the whole thing can go kaput and not reflect your chosen attributes.

  • Different browsers react just a bit differently with CSS styles. We’re going to show you the syntax that works best across different browsers. If you follow our syntax guidelines you’ll find it easier to design CSS to work across different platforms.

    What Do We Mean by Style?
    That’s a good question. In the case of CSS, “style” means everything that defines how your Web pages look. Fonts, spacing, and line height are all part of style and with CSS you can apply different attributes to every tag you use in your pages. If you wanted to set all your

    tags to display in 12-point Times New Roman with an indent on the first line, you can do that with CSS. In fact, here’s what the code for that would look like:

    P  {font-size: 12pt;      font-family: “Times New Roman”;      text-indent: 12pt}
    Pretty simple, isn’t it? We specified the font size, the font family and the text indent. The syntax looks a bit funny, but then it’s not HTML?it’s CSS.

    As you have probably figured out, “P” means the

    tag and the curly braces mark the start and end of the style declaration. Semi-colons separate each style element. Take special note that the last item closes with a close-brace, not a semicolon.

    If we wanted to use this same definition for

    tags we could change the “P” to “H1” and then all

    ‘s would appear on the page with these settings. The value 12pt, by the way, is short for 12 point. A point is a standard unit of measurement in typography and you can use it to specify type size with CSS. There is no space between the number and the measurement unit: 12pt.

    Where Do Styles Go?
    Now you may be wondering where you put these styles in your Web page. That’s an important question. There are three approaches you can take:

  • Set up an external .css file to hold your style definitions.

  • Declare your styles inline with the tags in ways we’ll demonstrate later.

  • Set them up in a style definition in the head of your document. Setting up a style definition in the head of your document is the method we’ll be using the most. Let’s look at how to do that now.

    Setting up a Style Declaration
    Setting up a style declaration is pretty straight-forward. You typically include it in your header information. To start a style declaration, open it with the HTML

    Notice that we ended our style declarations with the HTML end remark "-->" and the close style tag. This puts the rest of our page back into HTML mode so the browser can continue business as usual. In case you're curious, these are the style declarations that we are using for this page.

    Let's take a look though at what we just defined:

  • We set our default body text and our

    tag to display nearly identically. The difference? The paragraph style includes a text indent attribute, so that all paragraphs (

    ) will indent a little on the first line. The body style does not include the indent.

  • Both level one headlines (

    ) and level two (

    ) headlines are also defined and assigned a specific type size, face, style, and color.

  • Notice that we've tweaked the tag as well. With the anchor style we turned off underlining so that none of our anchors will appear underlined.

    Don't worry if you don't understand all of the attributes right now. You can look them up as you need them (see the style properties listed in the side menu bar) or refer to the CSS style properties reference table in the reference section of the Developer Zone.

    For now, we just wanted to show you how easy they are to use. You might cut and paste those lines into a document of your own and play with them to see what kind of effects you can get. We're betting you'll surprise yourself with just how easy this really is.

  • Dynamic Effects in 5 Minutes
    You've seen how easy it is to use CSS; now you'll see how easy it is to modify CSS on the fly for Dynamic HTML.

    Dynamic HTML (DHTML) lets you change the Web page based on what a reader does. It's a little like JavaScript, but it goes a step further and lets you change or update any element on the page, dynamically.

    One of the most desired interactions on a Web page is to have something change when the reader moves his or her mouse over it. This is called a mouseover event. With Dynamic HTML this effect is very easy to produce. That's because with DHTML, every element of a Web page is exposed via a structure called the Document Object Model (DOM). Don't be put off by the name?all Document Object Model really means is that you can control nearly everything on the page if you know how to address it.

    Every element on a Web page has a style associated with it. Even if you didn't declare a style, the browser has a default style for everything. For example, with just normal old HTML and no extra coding:

  • Links are underlined.
  • H1s are flush to the left side of the page.
  • Paragraphs use the browser's default typeface.
  • The body background is grey.

    The list goes on and on, but the point is that every element on the page has a style. Stylesheets, via CSS, let you change those. Now, DHTML lets you change those dynamically. To access these styles and change them dynamically, we need to know just two things:

    1.  The style property we want to change.

    2.  Just a smidgen of simple JavaScript.

    For our sample mouseover example we're going to change the color of our text. In scripting lingo we need to access "style.color" which is where the color of the text is kept. Here's the effect in action; run your mouse over the line of text that follows to see how it works:

    Mouse over this text

    Here's the simple code that let us do this:

    Mouse over this text

    See how easy it is? "onmouseover" is the event triggered by moving the mouse over the text and "onmouseout" is the event of moving the mouse out of the area. Events are what let us know that something has happened so that appropriate actions can follow.

    The code "this" is the reference for this particular object. Here, "this" refers to the level three heading. The code "style.color" refers to the color of the object "this" and allow us to change the level three heading's color.

    If we wanted to, we could have changed the background color instead. The line of text that follows shows the effect and the code shows how we created the effect:

    Mouse over this text

    Mouse over this text

    Any property you want to modify can be accessed in this manner.

    It's also easy to determine the name of the property for scripting. Here's a rule of thumb you can follow:

    To get the scripting property name for a style property, remove the hyphen from the style property name and capitalize the first letter of the word that follows the hyphen. For example:"text-decoration" becomes textDecoration. background-color become backgroundColor, etc.

    There you have it, five minutes of study and you can now do mouseover events with Dynamic HTML!

    A word of caution though. It might seem "cool" to change things like font size on the fly, but think about your end users before you do anything that might cause their text to crawl around their browser. The goal is to create dynamic, elegant and useful interfaces for the Web?not just to prove that you can create DHTML.

  • The Class System
    Many times you'll discover that you need variations of certain styles. For instance you might need two different styles of anchors, one that is the default style, and another with a variation for a different section of the same page. You might, for example, want it with a different background color used as a highlight. With classes, these variations are simple to set up. Here's what your style declaration might look like if you were creating a class of anchors named "highlighted":

    Notice that the class declaration is just like a normal declaration except that ".highlighted" is appended to the HTML tag name. In this case we've created a new class of anchor named "highlighted." Once we've set up a class, it's easy to call it in an HTML page. Here's how:
    A highlighted link
    And here's what it looks like:

    The Earth

  • Abolishing and Eliminating Redundancy
    Ok, I admit it. I'm tired of typing (or even cutting and pasting) the same style info into a document. It's time now for a better solution.

    Lucky for us there is a solution. Here's the code to put in your header:

    It's a pretty simple line of code but what it does is incredibly powerful. It links a stylesheet into your page. The stylesheet, in this case, is the file "styles/dynamic.css" It is ascii text and contains nothing but style rules for our page. The Web browser loads those rules and applies them to the current page.

    Here's a sample stylesheet:

    BODY {font-size: 12pt;       font-family: "Times New Roman";      line-height: 14pt;      background-image: URL(images/logo.gif);      background-position: center;      background-repeat: no-repeat;      background-position: center;      background-attachment: fixed}H1 {font-size: 20pt;      font-family: "Arial";      font-weight: bold;      color: 9966cc;      z-index: 0}  H2 {font-size: 15pt;      font-family: "Arial";      font-weight: bold;      margin-top: 30pt;      color: 9966cc}  P  {font-size: 12pt;       font-family: "Times New Roman";      line-height: 14pt;      text-indent: 12pt;      margin-top: 6pt}  PRE {font-size: 10pt;       font-family: "Courier";       line-height: 14pt;       color: red}       A  {text-decoration: none}
    Notice that there are no HTML tags in the file. It consists of just style attributes.

    The power of this may not be immediately apparent but consider this: You can link the same stylesheet to multiple pages. If you should need to change the look of your pages you no longer need to edit each individual file, just change the stylesheet. The changes will be applied to all documents that link to it.

    Combined with a little planning this can be a very powerful tool.

    Spanning the Web
    Short lesson this time. Really short.

    Ok, remember our friend

    that we've been using all along? Well he's got a sister named who works just like him, except she doesn't force new lines. So you can use inline in your text to assign styles and ID's to different parts of your documents that you can then manipulate.

    So, suppose you want to set a highlight on just one word in a paragraph, like we just did. Instead of setting a font tag, which really isn't what we needed, just use to mark the section. This also means that once you've marked a section you can perform many of the same DHTML and CSS style tricks you've learned.

    That's it for this lesson, short and sweet. The next lesson will provide you with some useful JavaScript.

    Expand Your Mind
    Wow, did you see that? (You are using IE4.0, right?) In this lesson we're going to show you how to do that one. If you missed it, then just click here and we'll show you again.

    We're using the letter-spacing attribute and changing it on the fly to expand the title heading of this page. It's pretty easy to do and you'll be able to cut & paste the javascript to put it in your own pages. Here it is:

    This function, called expandText, will work with any ID name you pass to it. The ID you modify doesn't have to be associated with a

    , you can associate it with an

    or anything else that you can control letter-spacing on. You'll need to pass 5 variables to the script when invoked:
    expandText('which',start,finish,step,speed);
    • which - the ID of the HTML you wish to modify
    • start - the value for the beginning letter-spacing (must be less than finish)
    • finish - the end value for letter-spacing (must be greater than start)
    • step - the increment to increase letter-spacing (1 is the smoothest)
    • speed - the speed in milliseconds to animate the expansion (1000=1 second)
    Once you've determined the setting, then just call the routine. Here's how we called the routine when our page loaded:
    Pretty simple, right? And pretty powerful too. You'll notice that we are setting our letter-spacing in pixels ("px" in the code). You can change that to one of the other units of measurement if you like. If you wanted to do this in points, just change "px" to "pt" and the letter-spacing will be adjusted with points.

    This core routine can be used to modify things other than letter-spacing and we'll be using it in some of our future examples. You might also modify it to contract text. It can be done with just 2 simple changes. Give it a try.

    Coffee Filters
    One of the marvelous features that Internet Explorer 4.0 (or higher) offers is something that called Multimedia Filters. While we're not sure what qualifies these filters as multimedia, we do know that they give us the ability to manipulate our Web page as though we were applying Photoshop-like filters for blurring, opacity, etc.

    Let's take a look at one now. Notice how the word coffee appears blurred? We'll bet you even noticed how both "coffees" look different. The top word is HTML text, the bottom word is an image created in Photoshop. We've used both types so that you can see how these filters act differently depending upon whether they are acting upon text or images, see below:


    coffee

    This is done with the simple application of the filter parameter to the CSS attributes of that division:

    coffee

    It's pretty simple when you know the attributes for the filter. In the case of blur we have add, direction, and strength.

    Add is whether or not the original is included in the final filter effect. A value of 0 means don't include the original and a value of 1 means that the original should be overlayed in the final effect.
    Here's what it looks like if we set Add to 0:


    coffee

    As you can see, this example makes it pretty obvious that the blur filter works best on images. The direction attribute should be a number between 0 and 360 indicating the direction of the blur. Strength is how strong the blur should be. Look at the example below, with direction set to 120 and strength set to 10:


    coffee

    Very Important: One thing that is extremely important to note is that you must specify a width for something that you want to apply a filter to. We're not sure why this CSS attribute is required, but we do know that without specifying width, none of these filters will have any affect.



    Let's take a look at some of the other filters now. Here's a fun one called glow:

     coffee

     

    coffee

    Color is the hexadecimal value for the color you wish the glow to be and strength is used to indicate how strong the glow should be.



    Similar to glow is the dropshadow filter:

    coffee

    coffee

    Just as glow did, dropshadow uses the color attribute. It also uses offx and offy which specify the number of pixels to offset the shadow. Finally, it uses positive with a value of either 1 or 0. A value of 1 means to shadow the visible (or positive) pixels and a value of 0 selects the invisible (or negative) pixels.



    The invert filter has no attributes but simply produces a negative color effect onto the section it is applied to:

    coffee

    coffee



    Xray is an odd filter. It is very much like invert, but it first turns the area to grayscale and then inverts it. Like invert it has no parameters. It looks like this when applied:

    coffee

    coffee



    And, since we've just seen something that has been turned to grayscale we should mention that there is indeed a grayscale filter. Once more, it is a filter with no attributes:

    coffee

    coffee



    There are attributeless filters for flipping content. They are fliph and flibv for horizontal and vertical flipping respectively.

    fliph:


    coffee

    coffee

    flipv:

    coffee

    coffee

    Those are the most basic filters and, as you can see, they hold a lot of potential. Moving the Heavens

    I know you've seen this trick before. I've broken out the image movement routine and will be showing you how to use it. As an added bonus you'll be happy to know that this one will work in Netscape Navigator 4.0 as well as Internet Explorer 4.0 or higher.

    Let's take a look at the code that allows this to work in both browsers:

    ie4 = ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4 ))ns4 = ((navigator.appName == "Netscape") && (parseInt(navigator.appVersion) >= 4 ))if (ns4) {    layerRef="document.layers";    styleRef="";} else {    layerRef="document.all";    styleRef=".style";}       

    This code starts with two browser detects so that it can determine if you have a DHTML capable browser. Then it sets some variables depending on which browser you have. The reason it must do this is that Navigator uses the document.layers object in it's Document Object Model for CSS positioning and Internet Explorer uses the document.all.id.styles object. Lucky for us we can work around that for compatibility. We're going to use those variables in the actual movement routine.

    Here's the movement routine:

    function moveDivision(which, start, finish, step, speed){    if (ie4 || ns4){    if (start < finish){       eval(layerRef + '["' + which +'"]' + styleRef + '.top = start');      eval(layerRef + '["' + which +'"]' + styleRef + '.left = start');      start=start+step;       setTimeout("moveDivision('"+which+"',"+start+","+finish+","+step+","+speed+")",speed);    }       }}

    I can't speak for anyone else, but I get pretty confused when I look at that code, mainly because of all the concantenation. If you look at the eval functions though you can see that we're using those compatability variables to make the right call depending on our browser. If you need to modify that section be very careful with your quotes.

    The real key to making this work is the arguments that we pass to the routine. Here's what they are and what they mean:

    • which - the id of the division you are moving
    • start - the starting position for top and left positions
    • finish - the ending position
    • step - how to count, usually by 1's
    • speed - how long in milliseconds before each step

    One limitation of this script is that it only works on diagonals. You could modify it easily enough so that only top or left were getting changed by deleting one or the other of the eval functions. This could give you a total of 8 possible directions you could move.

    The next thing you need to know is how to call it. Although you could call it on any event, we are using the body tag's onLoad event to start the action. This means that nothing happens until the page is fully loaded. By doing it this way we are assured that the user has all of the images and can actually see the moving division.

    That's how you get the JavaScript working but you can't forget to add the correct style attributes for the division you want to move. Here's the HTML for the division I'm using in this example:

    Make sure you specify values for all of those style parameters. The z-index value of 0 puts the division behind everything on this page. We've given the rest of the page a z-index of 10. We needed to do this for Navigator compatability. The entire text of the page is in a division with relative positioning. The seemed to be the only way that we could get Navigator to recognize z-indexing relative to the text on the page.

    You should be well armed now for moving heavenly bodies, or anything else you might want to move dynamically. So get out and start moving the web. Oh, and just to make it easier to cut and past, here's the entire JavaScript for making this work:

    The Right Alignment
    When you see DHTML used for animations and effects you most often see everything based on top left corner of the browser window. I suppose I could have gone along happily ever after basing everything on that location but I'm not one to settle for just what I'm handed; I always want more. Since I tell people to strive to create Liquid Web pages I thought I'd best learn to create a liquid DHTML page.

    I knew there was a way to determine the right and bottom edge location of the browser so I spent a morning pulling my hair and sifting through documentation in an effort to find out how. After several hours I had found my solution!

    It's really quite simple so I'm surprised that I had to look so hard to find an answer. Here's how to do it in IE4:

     rightEdge = document.body.offsetWidth;bottomEdge = document.body.offsetHeight;
    And since we want to keep pages compatible with both 4.0 browsers, here's how you do it using Netscape Navigator's DOM:
    rightEdge = innerWidth;bottomEdge = innerHeight;
    Knowing how to do that in both browsers means we can combine that information into one small JavaScript function that finds our edges for us:
    findEdges(){	if (navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4 ){		rightEdge = document.body.offsetWidth;		bottomEdge = document.body.offsetHeight;	} else {		rightEdge = innerWidth;		bottomEdge = innerHeight;	}}
    Pretty simple really, first check to see if the browser is IE4 or higher, if it is then set the edges the IE4 way, if it's not, then set the edges the NN4 way. It's important to remember that this code is 4.0 specific so make sure you're not calling this in a 3.0 or smaller browser.

    Now what can you do with this information? You can amaze your audience with Liquid DHTML. The possibilities are endless.

    devxblackblue

    About Our Editorial Process

    At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

    See our full editorial policy.

    About Our Journalist