Masthead

Lab: Using JavaScript to Access The Document Object Model (DOM)

The Document Object Model, or DOM, is the core of any web browser. When an HTML page is loaded into a browser, it is converted into a DOM. The DOM is what the browser displays and what the user interacts with. The power of the DOM is that we can use JavaScript to modify it and the user immediately sees the results. We can also add "handlers" to "widgets" in the DOM so that when the user clicks on a widget, something happens. This is how we make everything from moving maps to really annoying adds.

See the W3Schools Web Page on the DOM

HTML -> DOM

All web pages start out as HTML text documents. When the browser loads a web page it "parses" the HTML tags and converts each tag into a DOM "element.

With modern browsers, you can now see the contents of the DOM. Open a web page now and look through the contents of the DOM. Remember that the DOM was created from HTML initially but JavaScript can then modify the contents.

Accessing the DOM

Try the code below:

<!DOCTYPE html>
	<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script> var TheElement=document.getElementById("test"); TheElement.innerHTML="Hi"; </script>

</head>

<body> <div ID="test"> </div>

</body>
</html>

You may have been surprised if nothing happened. Open a debugger and refresh the page. You'll see there is an error. This is because the "<script>" code was executed as the page was read the first time. This means that the code was executed before our "div" tag was added to the DOM. To fix this, we need to add an "event handler" to the "body" of the HTML page that is executed after the body loads.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script> function OnLoad() { var TheElement=document.getElementById("test"); TheElement.innerHTML="Hi"; }
</script>
</head> <body onload="OnLoad()"> <div ID="test"> </div> </body> </html>

We have just opened up a whole world of being able to create HTML elements and then modify them with JavaScript. Take time now to create a series of HTML elements, add "IDs" to them, and then modify their behavior in the "OnLoad" function. This can include changing the color, HTML contents and just about anything else. Below are some examples, see the W3Schools web site for the entire set.

	TheElement.innerHTML="Hi"; 
TheElement.style.background="green"; // change the background color
TheElement.style.padding="10px"; // add space between the HTML content and the border
TheElement.style.margin="10px"; // add space around the entire DOM element
TheElement.style.fontSize="20px"; // set the size of the text
TheElement.style.border="solid 2px red"; // change the border

// set the position of the element to be fixed within the window

TheElement.style.position="absolute";
TheElement.style.top="100px";
TheElement.style.left="20px";
TheElement.style.width="300px";
TheElement.style.height="200px";

Event Handlers

In the example above, we added an "OnLoad()" function to the "body" element. This is called an "Event Handler" because it handles the "OnLoad" event. There are many events defined in HTML and all HTML elements support a set of events. You can add your JavaScript functions to these events.

On popular event is "onClick". This event is "triggered" when the user clicks on something. Search for "JavaScript onclick" on the web and you should be directed to the W3Schools web site. Read about the "onclick" event and then try their code sample. Then, add the code below into your HTML to add a button:

<input type="button" value="Change Image" onClick="ButtonClicked()">

Then, add the following function into your "scripts" section of your file:

function ButtonClicked()
{
var TheElement=document.getElementById("test");
TheElement.style.background="red";
}

Try adding additional buttons to change other attributes of the web page.

You can also add a text field and then get the value from the field. Add the following into your HTML;

<input id="BackgroundColor" type="text" value="purple">

And then use the value in your "ButtonClicked()" function:

function ButtonClicked()
{
var TheElement=document.getElementById("test");
var TheBackgroundColorElement=document.getElementById("BackgroundColor");
TheElement.style.background=TheBackgroundColorElement.value;
}

Now, try different colors for the background. Then, add additional text fields for different properties in the box.

Changing the Image in an "img" element

Some elements have additional properties, such as images, or "img"s,which has the "source" of the image. You can change the image on a page with the following.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script>
function ButtonClicked()
{
	var TheElement=document.getElementById("TestImage");
	TheElement.src="IEDeveloperTools.png";
}

</script>

</head>

<body>
<img ID="TestImage" src="IEDebugger.png">
<input type="button" value="Change Image" onClick="ButtonClicked()">
</body>
</html>

Visit the 3WSchools web site again and examine all the events that are available for HTML objects, especially buttons, images, and divs.

Animation (optional but fun)

We can now do some simple animation by setting the position of a "div" element and then moving it. We'll also need to use the "setTimeout()" function. "setTimeout()" will set a timer to run for the number of "milliseconds" that you specify and then it will call the function you passed into "setTimeout()". This allows us to do simple animation in a web page. Try the code below. It's pretty boring so you can spice it up by adding colors that change, changing the border size, the font size, or whatever you desire.

<!DOCTYPE html>
<html>
<head>
<title>Animated Box</title>
<script>
// Setup a counter to count the number of times we will run through the animation.
// Because this is outside the functions, it is available "globally" or anywhere 
// on this page.
var Counter=0;
/* 
* This is out function to perform the animation.  It is called when the "setTimeout()" 
* function terminates
*/
function Animate()
{
	// get the element
	var TheElement=document.getElementById("MovingBox");
	
	// get the current position of the "left" side of the element
	var CurrentLeft=TheElement.style.left;
	
	// the position of the left side will be formatted like "20px"
	// so we have to remove the "px" before we can do some math on the value
	// this line of code will strip off the last two characters and then
	// convert them to a integer and store the value in "CurrentLeft"
	CurrentLeft=parseInt(CurrentLeft.substring(0,CurrentLeft.length-2));
	
	// Set the HTML for the element to the left value so we can see it
	// This is also a nifty debugging trick
	TheElement.innerHTML=CurrentLeft;
	
	// Position the left side of the element (the element will immediately move!
	TheElement.style.left=(CurrentLeft+10)+"px";
	
	// If the counter is below our limit, move again
	if (Counter<5) // change this value to have the box move further
	{
		// increment the counter so we don't animate forever
		Counter=Counter+1;
	
		// set the time out again and have it call this function again after 1 second.
		setTimeout(Animate,1000);
	}
}
/*
* The functiont that is called after the page body has loaded and setup in the DOM
*/
function OnLoad()
{
	// Get the element
	var TheElement=document.getElementById("MovingBox");
	
	// Put something in the element to start it started
	TheElement.innerHTML="Hi";
	
	// Set the position to "absolute" so we can position it with left, top, width, and height
	TheElement.style.position="absolute";
	TheElement.style.top="10px";
	TheElement.style.left="20px";
	TheElement.style.width="300px";
	TheElement.style.height="200px";
	
	// Set a timer for 1000 milisecones (1 second) and have it call the Animate function when 
	// the timer goes off
	setTimeout(Animate,1000);
}
</script>
</head>

<body onLoad="OnLoad()">

<!-- This is an HTML comment and below is our "moving box" element -->

<div ID="MovingBox">
</div>

</body>
</html>

 

Note: The information above will only get you so far. I highly recommend spending some time with the W3Schools web site and especially their "Try It" web pages. Then, think of what you want to do on a page.

© Copyright 2018 HSU - All rights reserved.