DHTML Examples |
Example 1: Setting title for a page (usual way):
<HTML> <HEAD> <TITLE>This title was created using a tag </TITLE> </HEAD> </HTML> |
Example 2: Let's use DHTML now:
<SCRIPT language = JavaScript> document.title = "And this is a DHTML title" // Accessing Title property of the Document object </SCRIPT> |
(Both example files have the *.htm extension and result in entitling your page in browser).
What did we actually do? In Example 1 we used an HTML tag <TITLE> to access the Title property of the Document object which represents the whole HTML page you view in the browser. In Example 2 we basically did the same thing, but we used JavaScript to access this property directly instead of the accustomed <TITLE> tag. And because there are more than a hundred of objects, tons of different properties, methods and events it's really easy to do amazing things visitors of your page will surely enjoy! Consider the following code which retrieves client desktop settings:
Example 3: Getting desktop settings:
<SCRIPT language = JavaScript> function getdesktop() { var x = window.screen.width // Getting the width in pixels var y = window.screen.height // Getting the height in pixels var c = window.screen.colorDepth // Getting the color depth in bits per pixel x.toString() // Converting to string y.toString() // Converting to string c.toString() // Converting to string window.alert ("You current desktop settings are: "+x+"x"+y+"x"+c+" bpp!") // Output } </SCRIPT> <HTML> <HEAD> <TITLE>Getting desktop settings</TITLE> </HEAD> <BODY> <FORM> <INPUT type = button value = "Find out your desktop settings!" onclick = getdesktop()></INPUT> </FORM> </BODY> </HTML> |
Here we create a function which is called whenever the button is pressed (OnClick event is fired). This function getdesktop() initializes three variables x, y, and c which get three properties of Window.screen object respectively. Window.screen object itself contains information about the client's screen and rendering abilities and we retrieve width, height and color depth from it. Then we convert all our variables to strings and print them out using Alert method.
Of course this example could be entertaining but is not very useful. But with the same technique you can redirect visitor of your page depending on his/her current desktop resolution!
Example 4: Smart navigation:
<SCRIPT language = JavaScript> if ( window.screen.width <= 640 ) window.navigate ("low_version.htm") // If width <= 640 if ( window.screen.width >= 1024 ) window.navigate ("high_version.htm") // If width >= 1024 else window.navigate ("default.htm") // Open default.htm if width is between 640 and 1024 </SCRIPT> |
Method Navigate is used to go to another URL in the same window. So this little script gets client's desktop settings and then loads optimized version of the page.
It's also very easy to write to the status bar of the browser. All you have to do is to access the Status property of Window object:
Example 5: Writing to status bar:
<SCRIPT language = JavaScript> function loadinfo() { window.status = "Page is loaded!" // Accessing Status property of the Window object } </SCRIPT> <HTML> <HEAD> <TITLE>Writing to status bar</TITLE> </HEAD> <BODY onload = loadinfo()> </BODY> </HTML> |
The function loadinfo() is called when onload event is fired (That means the page is 100% loaded). Then we pass the string "Page is loaded!" and it appears in the status bar of the browser.
Now when you already know how to write to the status bar, let's create a very simple program which shows current time. To get the time you can use methods getHours, getMinutes and getSeconds of the Date object. Here's the final code:
Example 6: Status-bar watch:
<SCRIPT language = JavaScript> function time() { var d = new Date() // Creating the Date object var result = "The time is: " // Our result string result += d.getHours() + " : " // Getting the hours and adding ":" result += d.getMinutes() + " : " // Getting the minutes and adding ":" result += d.getSeconds() // Getting the seconds window.status = result // Writing result to the status bar setTimeout("time()", 1000 ) // Calling the function again after 1000 ms (1 second) } </SCRIPT> <HTML> <HEAD> <TITLE>Status bar watch</TITLE> </HEAD> <BODY onload = time()> </BODY> </HTML> |
The most important thing about this little script is the usage of setTimeout method of the Window object. This method evaluates an expression after a specified number of milliseconds has elapsed. In our case it calls function time() each 1000 ms which is equal to 1 second.
With JavaScript you can also manipulate the main view window of client browser. You can easily resize it, move it or scroll it. For these purposes you can resizeTo, moveTo and scrollTo, and resizeBy, moveBy and scrollBy. ResizeTo method sets the size of the window dimensions to the specified x and y pixel sizes, on the other hand resizeBy changes the size of the window by the specified offset relatively to current values. The same story is with the other two methods, but moveTo (and moveBy) actually moves the window, and scrollTo scrolls it. Look at this sample to get more information on using resize and move (scrollTo and scrollBy are left up to the reader):
Example 7: Playing with browser window:
<SCRIPT language = JavaScript> window.resizeTo ( window.screen.width/4, window.screen.height/4 ) // Shrinking the window window.moveTo ( 0, 0 ) // Moving the window in the upper-left corner var current_x = 0 // Current horizontal position var current_y = 0 // Current vertical position var screen_x = window.screen.width - window.screen.width/4 //Maximum horizontal position var screen_y = window.screen.height - window.screen.height/4 //Maximum vertical position while (current_x < screen_x) // While it's possible to move the window to the right { window.moveBy (1, 0) // Move by one pixel current_x ++ // Increase current position by one } while (current_y < screen_y) // While it's possible to move the window to the bottom { window.moveBy (0, 1) // Move by one pixel current_y ++ // Increase current position by one } while (current_x > 0) // While it's possible to move the window to the left { window.moveBy (-1, 0) // Move by one pixel current_x -- // Decrease current position by one } while (current_y > 0) // While it's possible to move the window upwards { window.moveBy (0, -1) // Move by one pixel current_y -- // Decrease current position by one } window.resizeTo (window.screen.width, window.screen.height) // Make it full-screen </SCRIPT> <HTML> <HEAD> <TITLE>Running window</TITLE> </HEAD> <BODY> <CENTER><H3> Welcome to sample page!</H3></CENTER> </BODY> </HTML> |
Hey, this is interesting! In the beginning of our script we shrink the browser window and place it in the upper-left corner of the desktop. Then we retrieve screen properties, define maximum x- and y-values for our window and move it in four while-cycles until the maximum value is reached. Quite an impressive way to decorate your homepage (I advise you to click View button right now)!
With JavaScript you can easily determine which browser is used to view your page. All you have to do is to request window.navigator.userAgent property. It returns a string which represents the user-agent header. From this string it's easy to get version and type of the client browser. Let's find out whether Internet Explorer is used:
Example 8: Determining the browser type:
<SCRIPT language = JavaScript> function browser_type() { var ie = false // will be true, if it's IE var ua = window.navigator.userAgent // Requesting the user-agent header if (ua.indexOf ("MSIE") > 0) ie = true // If "MSIE" is inside the string, then it's IE! if (ie==true) alert ("You are running IE!") // Alerting results else alert ("You are not!") } </SCRIPT> <HTML> <HEAD> <TITLE>Your browser type</TITLE> </HEAD> <BODY onload = browser_type()> </BODY> </HTML> |
The variable ua receives the user-agent header. Then we use indexOf method, which returns a positive number if "MSIE" was found in this string. Alert method informs user which browser he's using.
But if you'd like to know the specific version of the browser then it's a bit more sophisticated task. Here is how to do it:
<SCRIPT language = JavaScript> var version // Will have the version number var ua = window.navigator.userAgent // Requesting the user-agent header if (ua.indexOf("Navigator")>0) // If it's Netscape Navigator... { version = parseInt(ua.substring (8, ua.indexOf ("."))) // Retrieving number from the string alert ("The version of your NN browser is: "+version) // Alerting results } else if (ua.indexOf("MSIE")>0) // If it's IE... { version = parseInt(ua.substring (ua.indexOf("MSIE")+5,ua.indexOf("MSIE")+8)) // Retrieving number alert ("The version of your IE browser is: "+version) // Alerting results } else alert ("You are not using NN or IE!") </SCRIPT> |
Netscape Navigator and MS Internet Explorer return different userAgent strings. That's why we have to know which browser is used and then examine it. So, for NN:
In this odd-looking expression "parseInt (ua.substring (8, ua.indexOf (".")))" we retrieve part of the userAgent string between position 8 and the first dot. Why? The answer is really simple. It seems natural to suppose that any string starts with "Mozilla/" (8 digits) and then the version number is placed. We retrieve everything up to the dot (e.g. 4.6 turns into 4). Finally we convert this 4 (which is originally a string type) to integer with parseInt method.
For Internet Explorer we basically did the same thing, but the version number has another position. To determine it we first get the position of "MSIE" string with ua.indexOf("MSIE") method, and then retrieve everything between offsets 5 and 8. That's exactly the place where the version number for IE is located.
Well, now it's the right time for the most interesting way to use JavaScript and DHTML object model. The best thing about it is that it's easy, clear and powerful. Simply saying, you can change all the tags you like on the fly. You only need to set special id for the tag you want to change and then use very simple script with outerHTML method as shown below:
Example 9: Changing tags on the fly:
<SCRIPT language = JavaScript> function replace() { document.all.font1.outerHTML = "<FONT size = 5 color = red><i>The tag has been dynamically changed!</i></FONT>" // Using outerHTML method } </SCRIPT> <HTML> <HEAD> <TITLE>Changing tags on the fly</TITLE> </HEAD> <BODY> <CENTER> <FONT face=arial size= 3 id = font1 onmouseover = replace()>This is result of original tag. Move mouse pointer over! </FONT> </CENTER> </BODY> </HTML> |
As you can see I've added id = font1 to the <FONT> tag. The function replace() is called when mouse pointer moves over the text and it replaces the whole tag (with id == font1) with argument string. To make it you can use All collection of the Document object and outerHTML method. So basically general syntax will always be like: document.all.[tag id].outerHTML = "everything you'd like". I guess you'll surely do a couple of nice things with this technology!
Finally I'll show you how to make a new browser window. It's so easy that you may find it not interesting at all, but it can be very useful, so watch this: window.open ("yourURL.htm"). That's it if you like default settings for your new window. Take a look at the last example which also demonstrates that you can make JavaScript calls not only within <SCRIPT> block:
Example 10: Opening links in new window:
<HTML> <HEAD> <TITLE>Opening links in new windows</TITLE> </HEAD> <BODY> <P onclick = 'window.open ("page1.htm")'><b>Click on this to see page one</b></P> <P onclick = 'window.open ("page2.htm")'><b>Click on this to see page two </b></P> <P onclick = 'window.open ("page3.htm")'><b>Click on this to see page three </b></P> </BODY> </HTML> |
JavaScript code is inserted right into HTML, but it works. As you click any of the text lines a new window is opened. It can't go to the needed URL, naturally, but the main idea should be obvious.