You are on page 1of 17

DHTML Tutorial

DHTML Tutorial
DHTML is the art of making HTML pages dynamic!

DHTML is a combination of technologies used to create dynamic and


interactive Web sites.

To most people DHTML means a combination of HTML, Style Sheets and


JavaScript.

Start learning DHTML now!

DHTML DOM Reference

At W3Schools you will find a complete DHTML DOM reference of all the DOM objects, along with
their properties and methods.

DHTML DOM Reference

DHTML Examples

Learn by 100 examples! With our editor, you can edit the source code, and click on a test button to
view the result.

• DHTML Examples
• DHTML DOM Examples

Introduction to DHTML

What you should already know

Before you continue you should have a basic understanding of the following:

• HTML
• CSS
• JavaScript

If you want to study these subjects first, find the tutorials on our Home Page.

DHTML is NOT a W3C Standard

DHTML stands for Dynamic HTML.

DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing
term" - used by Netscape and Microsoft to describe the new technologies the 4.x generation
browsers would support.

1
DHTML is a combination of technologies used to create dynamic Web sites.

To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript.

W3C once said: "Dynamic HTML is a term used by some vendors to describe the combination of
HTML, style sheets and scripts that allows documents to be animated."

DHTML Technologies

With DHTML a Web developer can control how to display and position HTML elements in a browser
window.

HTML 4.0

With HTML 4.0 all formatting can be moved out of the HTML document and into a separate style
sheet. Because HTML 4.0 separates the presentation of the document from its structure, we have
total control of presentation layout without messing up the document content.

Cascading Style Sheets (CSS)

With CSS we have a style and layout model for HTML documents.

CSS was a breakthrough in Web design because it allowed developers to control the style and
layout of multiple Web pages all at once. As a Web developer you can define a style for each HTML
element and apply it to as many Web pages as you want. To make a global change, simply change
the style, and all elements in the Web are updated automatically.

The Document Object Model (DOM)

DOM stands for the Document Object Model.

The HTML DOM is the Document Object Model for HTML.

The HTML DOM defines a standard set of objects for HTML, and a standard way to access and
manipulate HTML objects.

"The W3C Document Object Model (DOM) is a platform and language neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a
document".

JavaScript

Allows you to write code to control all HTML elements.

DHTML Technologies in Netscape 4.x and Internet Explorer 4.x

Netscape 4.x Cross-Browser DHTML Internet Explorer 4.x


• JSS (JavaScript Style • CSS1 • Visual Filters (allow you to
Sheets) (allows you to • CSS2 (allows you to apply visual effects to text
control how different control how different and graphics)
HTML elements will be HTML elements will be
displayed) displayed) • Dynamic CSS (allows you
• CSS Positioning (allows

2
you to control element
positioning and visibility) to control element
• Layers (allows you to
control element positioning and visibility)
positioning and visibility) • JavaScript

Note: Problems with coding DHTML technologies WILL occur as long as each browser creates its
own proprietary features and technology that is not supported by other browsers. A Web page may
look great in one browser and horrible in another.

DHTML CSS Positioning (CSS-P)

CSS is used to style HTML elements.

Examples

Note: Most of the DHTML examples require IE 4.0+, Netscape 7+, or Opera 7+!

position:relative
How to position an element relative to its normal position.

position:relative
How to position all headings relative to their normal position.

position:absolute
How to position an element using an absolute value.

(You can find more examples at the bottom of this page)

Which Attributes can be Used with CSS-P?

First, the element must specify the position attribute (relative or absolute).

Then we can set the following CSS-P attributes:

• left - the element's left position


• top - the element's top position
• visibility - specifies whether an element should be visible or hidden
• z-index - the element's stack order
• clip - element clipping
• overflow - how overflow contents are handled

Position

The CSS position property allows you to control the positioning of an element in a document.

position:relative

3
The position:relative property positions an element relative to its current position.

The following example positions the div element 10 pixels to the right from where it's normally
positioned:

div
{
position:relative;
left:10;
}

position:absolute

The position:absolute property positions an element from the margins of the window.

The following example positions the div element 10 pixels to the right from the left-margin of its
containing block:

div
{
position:absolute;
left:10;
}

Visibility

The visibility property determines if an element is visible or not.

visibility:visible

The visibility:visible property makes the element visible.

h1
{
visibility:visible;
}

visibility:hidden

The visibility:hidden property makes the element invisible.

h1
{
visibility:hidden;
}

Z-index

The z-index property is used to place an element "behind" another element. Default z-index is 0.
The higher number the higher priority. z-index: -1 has lower priority.

4
h1
{
z-index:1;
}
h2
{
z-index:2;
}

In the example above, if the h1 and h2 elements are positioned on top of each other, the h2
element will be positioned on top of the h1 element.

Filters

The filter property allows you to add more style effects to your text and images.

h1
{
width:100%;
filter:glow;
}

Note: Always specify the width of the element if you want to use the filter property.

The example above produces this output:

Header

Different Filters

Note: Some of the Filter properties will not work unless the background-color property is set to
transparent!

Property Argument Description Example


alpha opacity Allows you to set the opacity of the filter:alpha(opacity=20,
finishopacity element finishopacity=100, style=1,
style startx=0,
startx starty=0, finishx=140,
starty finishy=270)
finishx
finishy
blur add Makes the element blur filter:blur(add=true, direction=90,
direction strength=6);
strength
chroma color Makes the specified color transparent filter:chroma(color=#ff0000)
fliph none Flips the element horizontally filter:fliph;
flipv none Flips the element vertically filter:flipv;
glow color Makes the element glow filter:glow(color=#ff0000,
strength strength=5);
gray none Renders the element in black and white filter:gray;
invert none Renders the element in its reverse color filter:invert;
and brightness values

5
mask color Renders the element with the specified filter:mask(color=#ff0000);
background color, and transparent
foreground color
shadow color Renders the element with a shadow filter:shadow(color=#ff0000,
direction direction=90);
dropshadow color Renders the element with a dropshadow filter:dropshadow(color=#ff0000,
offx offx=5, offy=5, positive=true);
offy
positive
wave add Renders the element like a wave filter:wave(add=true, freq=1,
freq lightstrength=3, phase=0,
lightstrength strength=5)
phase
strength
xray none Renders the element in black and white filter:xray;
with reverse color and brightness values

Background

The background property allows you to select your own background.

background-attachment:scroll

The background scrolls along with the rest of the page.

background-attachment:fixed

The background does not move when the rest of the page scrolls.

More Examples

Visibility
How to make an element invisible. Do you want the element to show or not?

Z-index
Z-index can be used to place an element "behind" another element, using Z-index priority.

Z-index
Check that the elements now have changed their Z-index priority.

Cursors
Change the style of the mouse cursor with CSS.

Filters
Change the style of your headings using the filter property.

Filters on Images
The filter property can also be used on images, here are some filter examples which look good on
images.

Watermark
A background picture that does not move when the rest of the page is scrolling.

6
DHTML Document Object Model

The Document Object Model gives us access to every element in a document.

Examples

Note: Most of the DHTML examples require IE 4.0+, Netscape 7+, or Opera 7+!

Element access
How to access an element and change the style.

Attribute change
How to access an image element and change the "src" attribute.

innerHTML
How to access and change the innerHTML of an element.

How to access an element?

The element must have an id attribute defined and a scripting language is needed. JavaScript is the
most browser compatible scripting language, so we use JavaScript.

<html>
<body>
<h1 id="header">My header</h1>
<script type="text/javascript">
document.getElementById('header').style.color="red";
</script>
</body>
</html>

The script changes the color of the header element, and produces this output.

My header

DHTML Event Handlers

With an event handler you can do something with an element when an event occurs.

Examples

Note: Most of the DHTML examples require IE 4.0+, Netscape 7+, or Opera 7+!

onmouseover & onmouseout


How to change the color of an element when the cursor moves over and out of an element.

7
onclick
Turn on the light! How you can change an image when you click on it, and back to the original
image when you click on it again.

onmousedown & onmouseup


This time the light is on only when you hold the mouse button down.

onload
Displays an alert box when the page has finished loading.

Event handlers

With an event handler you can do something with an element when an event occurs: when the user
clicks an element, when the page loads, when a form is submitted, etc.

<h1 onclick="style.color='red'">Click on this text</h1>

The example above defines a header that turns red when a user clicks on it.

You can also add a script in the head section of the page and then call the function from the event
handler:

<html>
<head>
<script type="text/javascript">
function changecolor()
{
document.getElementById('header').style.color="red";
}
</script>
</head>
<body>
<h1 id="header" onclick="changecolor()">
Click on this text</h1>
</body>
</html>

HTML 4.0 Event Handlers

Event Occurs when...


onabort a user aborts page loading
onblur a user leaves an object
onchange a user changes the value of an object
onclick a user clicks on an object
ondblclick a user double-clicks on an object
onfocus a user makes an object active
onkeydown a keyboard key is on its way down
onkeypress a keyboard key is pressed
onkeyup a keyboard key is released
a page is finished loading. Note: In Netscape this event occurs during
onload
the loading of a page!
onmousedown a user presses a mouse-button
onmousemove a cursor moves on an object

8
onmouseover a cursor moves over an object
onmouseout a cursor moves off an object
onmouseup a user releases a mouse-button
onreset a user resets a form
onselect a user selects content on a page
onsubmit a user submits a form
onunload a user closes a page

You Have Learned DHTML, Now What?

DHTML Summary

This tutorial has taught you how to use DHTML to create more dynamic and interactive Web sites.

You have learned how to use the combination of HTML, CSS and JavaScript to animate HTML
documents.

For more information on DHTML, please look at our DHTML examples and our DHTML reference.

Now You Know DHTML, What's Next?

The next step is to learn about the HTML DOM and ASP.

HTML DOM

The HTML DOM defines a standard way for accessing and manipulating HTML documents.

The HTML DOM is platform and language independent and can be used by any programming
language like Java, JavaScript, and VBScript.

If you want to learn more about the DOM, please visit our HTML DOM tutorial.

ASP

While scripts in an HTML file are executed on the client (in the browser), scripts in an ASP file are
executed on the server.

With ASP you can dynamically edit, change or add any content of a Web page, respond to data
submitted from HTML forms, access any data or databases and return the results to a browser,
customize a Web page to make it more useful for individual users.

Since ASP files are returned as plain HTML, they can be viewed in any browser.

If you want to learn more about ASP, please visit our ASP tutorial.

DHTML DOM Objects

9
With JavaScript you can access and manipulate all of the HTML DOM objects.

HTML DOM Objects

The HTML DOM is a W3C standard and it is an abbreviation for the Document Object Model for
HTML.

The HTML DOM defines a standard set of objects for HTML, and a standard way to access and
manipulate HTML documents.

All HTML elements, along with their containing text and attributes, can be accessed through the
DOM. The contents can be modified or deleted, and new elements can be created.

The HTML DOM is platform and language independent. It can be used by any programming
language like Java, JavaScript, and VBScript.

Follow the links below to learn more about how to access and manipulate each DOM object with
JavaScript:

Object Description
Anchor Represents an HTML a element (a hyperlink)
Applet Represents an HTML applet element. The applet element is used to place
executable content on a page
Area Represents an area of an image-map. An image-map is an image with
clickable regions
Base Represents an HTML base element
Basefont Represents an HTML basefont element
Body Represents the body of the document (the HTML body)
Button Represents a push button on an HTML form. For each instance of an HTML
<input type="button"> tag on an HTML form, a Button object is created
Checkbox Represents a checkbox on an HTML form. For each instance of an HTML
<input type="checkbox"> tag on an HTML form, a Checkbox object is
created
Document Used to access all elements in a page
Event Represents the state of an event, such as the element in which the event
occurred, the state of the keyboard keys, the location of the mouse, and
the state of the mouse buttons
FileUpload For each instance of an HTML <input type="file"> tag on a form, a
FileUpload object is created
Form Forms are used to prompt users for input. Represents an HTML form
element
Frame Represents an HTML frame
Frameset Represents an HTML frameset
Hidden Represents a hidden field on an HTML form. For each instance of an HTML
<input type="hidden"> tag on a form, a Hidden object is created
History A predefined object which can be accessed through the history property of
the Window object. This object consists of an array of URLs. These URLs are
all the URLs the user has visited within a browser window
Iframe Represents an HTML inline-frame
Image Represents an HTML img element
Link Represents an HTML link element. The link element can only be used within

10
the <head> tag
Location Contains information about the current URL
Meta Represents an HTML meta element
Navigator Contains information about the client browser
Option Represents an option in a selection list on an HTML form. For each instance
of an HTML <option> tag in a selection list on a form, an Option object is
created
Password Represents a password field on an HTML form. For each instance of an
HTML <input type="password"> tag on a form, a Password object is
created
Radio Represents radio buttons on an HTML form. For each instance of an HTML
<input type="radio"> tag on a form, a Radio object is created
Reset Represents a reset button on an HTML form. For each instance of an HTML
<input type="reset"> tag on a form, a Reset object is created
Screen Automatically created by the JavaScript runtime engine and it contains
information about the client's display screen
Select Represents a selection list on an HTML form. For each instance of an HTML
<select> tag on a form, a Select object is created
Style Represents an individual style statement. This object can be accessed from
the document or from the elements to which that style is applied
Submit Represents a submit button on an HTML form. For each instance of an HTML
<input type="submit"> tag on a form, a Submit object is created
Table Represents an HTML table element
TableData Represents an HTML td element
TableHeader Represents an HTML th element
TableRow Represents an HTML tr element
Text Represents a text field on an HTML form. For each instance of an HTML
<input type="text"> tag on a form, a Text object is created
Textarea Represents an HTML textarea element
Window Corresponds to the browser window. A Window object is created
automatically with every instance of a <body> or <frameset> tag

DHTML Examples

Note: Most of the examples require IE 4.0+, Netscape 7+, Mozilla, Firefox 1.0, or Opera 7+!

CSS

Position:relative
Position:relative
Position:absolute
Visibility
Z-index
Z-index Vice Versa
Cursors
Watermark
Change background color

CSS Filter Property (IE only)

11
Filters
Filters on Images
Filter:mask image
Filter:mask text
Filter light effect
Filter moving light effect
Glowing header
Drop shadow header
From black and white to color
Gradually show image
Negative image
XRay image
The mask filter
Glowing link
Drop shadow link
Wave link
Shadow link
Alpha image link
Gray image link

Events

onload
onunload
onchange
onsubmit
onreset
onselect
onblur
onfocus
onkeydown
onkeyup
onkeydown vs onkeyup
onkeypress
onmouseover & onmouseout
onclick
ondblclick
onmousedown & onmouseup
onmousemove
Disable right-click IE only

Text

Element access
Attribute change
innerHTML access
Change innerHTML
Change position
onmousemove
onload & onunload
Tooltip
Typewrite message
Bigger text
Scrolling text
Blinking header

Input Forms

Identical forms
Identical forms 2

12
Change background color of an input field
Change text color of an input field
Insert background image to an input field
Change background color of a radio button IE and Opera only
Insert background image to a radio button IE and Opera only
Select all check-boxes
Change background color of a checkbox IE7 and Opera only
Insert background image to a checkbox IE and Opera only
Change background color of a button
Change text color of a button
Insert background image to a button
Change background color of a drop-down list
Change text color of a drop-down list
Change background color of a textarea
Change text color of a textarea
Insert background image to a textarea

Images

Preload image
Change the size of an image
Change the source of an image
Change the size & the source of an image
Change the position of an image
Change the background image
Moving image
Drag and drop the image IE and Opera only
Image viewer
A button with a background image IE and Opera only
Shaking image
Digital clock

Window

Shake the window

Links

Text transform
Letter spacing
Blinking link
Shaking link
Random Banner

Menus

Top navigation IE only


Left navigation IE and Opera only
Drop down navigation (select box)
Top drop down
Always-on-top
Inset borders IE and Opera only
Description menu
Description image
Cursor description
Cursor image
Gray/Color image menu IE only
Sliding Vertically IE and Opera only
Click sliding Vertically IE and Opera only

13
Sliding horizontal
Click sliding horizontal

Cursor

Cursor position
Cursor text
Cursor image
Cursor trail IE only

Page-enter Effects (IE only)

Fade in
Square in
Square out
Circle in
Circle out
Curtain up
Curtain down
Curtain right
Curtain left
Vertical blinds
Horizontal blinds
Boxy vertical blinds
Boxy horizontal blinds
Pulverized
Elevator close
Elevator open
Elevator horizontal close
Elevator horizontal open
Diagonal top right
Diagonal bottom right
Diagonal top left
Diagonal bottom left
Horizontal lines
Vertical lines
Random

DHTML DOM Examples

Anchor Object

Change text, URL, and target attribute of a link


Using focus() and blur()
Add an accessKey to a link

Document Object

Write text to the output


Write text with formatting to the output
Return the title of a document
Return the URL of a document
Return the referrer of a document
Return the domain name of the document's server

14
Use getElementById()
Use getElementsByName()
Open a new document, specify MIME type and add some text
Return the number of anchors in a document
Return the innerHTML of the first anchor in a document
Count the number of forms in a document
Access an item in a collection
Count the number of images in a document

Event Object

Which mouse button was clicked?


What are the coordinates of the cursor?
What is the unicode of the key pressed?
What are the coordinates of the cursor, relative to the screen?
What are the coordinates of the cursor?
Was the shift key pressed?
Which element was clicked?
Which eventype occured?

Form and Form Input Objects

View and change the action URL of a form


View the method that is to be used when sending form data
Alert id, type, and value of a Button object + disable button
Check and uncheck a checkbox
Checkboxes in a form
Checkbox - If the user clicks in a checkbox, the content of the text fields are converted to
uppercase.
Radio buttons
Reset a form
Submit a form
Form validation
Set focus to an input field when the page loads
Select the content of an input field
Dropdown list in a form
Another dropdown list
A dropdown menu
Jump to the next field when the current field's maxlength has been reached
Add accessKeys to form fields

Frame, Frameset, and IFrame Objects

Resizable and not resizable frames


Frames with and without scrollbars
Change the source / URL of two frames
Break out of a frame
Update two iframes

Image Object

Change the height and width of an image


Change the src of an image

Location Object

Send the client to a new location / URL


Reload a page

15
Break out of a frame
Anchors array - This example opens two windows. The first window contains four buttons and the
second window defines four anchors from 0 to 3. When a button is clicked in the first window, the
onclick event handler goes to the specified anchor in the second window.

Navigator Object

Detect the visitor's browser and browser version


More details about the visitor's browser
All details about the visitor's browser
Alert user, depending on browser

Option and Select Objects

Disable and enable a dropdown list


Get the id of the form that contains the dropdown list
Get the number of options in the dropdown list
Turn the dropdown list into a multiline list
Select multiple options in a dropdown list
Alert the selected option in a dropdown list
Alert the index of the selected option in a dropdown list
Change the text of the selected option
Remove options from a dropdown list

Screen Object

Detect details about the client's screen

Table, TableHeader, TableRow, TableData Objects

Change the width of a table border


Change the cellPadding and cellSpacing of a table
Specify frames of a table
Specify rules for a table
InnerHTML of a row
InnerHTML of a cell
Create a caption for a table
Delete rows in a table
Add rows to a table
Add cells to a table row
Align the cell content in a table row
Vertical align the cell content in a table row
Align the cell content in a single cell
Vertical align the cell content in a single cell
Change the content of a table cell
Change the colspan of a table row

Window Object

Display an alert box


Alert box with line-breaks
Display a confirm box
Display a prompt box
Open a new window when clicking on a button
Open a new window and control its appearance
Open multiple windows with one click
Send the client to a new location / URL
Reload a page

16
Write some text in the windows status bar
Print a page
Break out of a frame
Resize a window
Resize a window to a specified size
Scroll the window
Scroll the window to a specified position
Simple timing
Another simple timing
Timing event in an infinite loop
Timing event in an infinite loop - with a Stop button
A clock created with a timing event
Create a pop-up

17

You might also like