
One of the most useful features of client-side programs like JavaScript is that they can be used to dynamically modify web page user interfaces. Although server-side programs like PHP or Perl can also be used to modify Web page elements, their use requires a server request, a process that typically interrupts the user experience. Dynamic page elements, such as expanding banners, extending text and changing layouts are well suited for a language that immediately and directly responds to user interaction with page changes.
Instructions
Things You'll Need
- text editor
- Web browser with JavaScript enabled
- 1Open a text editor, and create a new file named expandBanner.html. In most text editors, create new files by selecting “New” from the “File” menu. Add some basic HTML tags to the file, including “<html>,” “<head>,” “</head>,” “<body>,” “</body>” and “</html>.”<html>
<head></head>
<body></body>
</html> - 2Add a “<div>” tag between expandBanner.html’s “<body>” and “</body>” tags. Assign the following attributes to the <div> tag: id; "mybanner," style; "background:blue," "border:1px solid," "height:30px" and "width:100px." Add a closing “</div>” tag to complete the banner. While the "id" attribute must be "mybanner," the style attribute values can be changed to suit the user interface.<div id="myBanner" style="background:blue;border:1px solid;height:30px;width:100px;">
</div> - 3Add an anchor tag (“<a>”) after the close “</div>” tag. Set the anchor tag’s “href” attribute to “#,” give the anchor the text “Click to Expand Banner,” and close the “</a>” tag.<a href="#">Click to Expand Banner</a>
- 4Add an “onclick” event to the anchor tag that calls a function named “expandBanner.”<a href="#" onclick="expandBanner()">Click to Expand Banner</a>
- 5Add an open JavaScript delimiter (“<script type="text/javascript">") and a closing JavaScript delimiter (“</script>”) to expandBanner.html. Place the delimiters between the “<head>” and “</head>” tags.<script type="text/javascript">
</script> - 6Add a function named “expandBanner” between expandBanner.html’s “<script type="text/javascript">” and “</script>” tags. This function sets focus to and expands the “mybanner” div by changing its width from 100px to 200px. Save and close expandBanner.html. After step 6, expandBanner.html appears as shown below:<html>
<head>
<script type="text/javascript">
function expandBanner()
{
document.getElementById('myBanner').style.width = '200px';
}
</script>
</head>
<body>
<div id="myBanner" style="background:blue;border:1px solid;height:30px;width:100px;">
</div>
<a href="#" onclick="expandBanner()">Click to Expand Banner</a>
</body>
</html> - 7Open expandBanner.html in a web browser. Click on the “Click to Expand Banner” hyperlink and verify that the blue banner expands from 100px to 200px.
- 1