Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Workshop: Creating Back and Forward Buttons

One common use for the back and forward methods of the history object is to add your own Back and Forward buttons to a Web document. This can improve the user interface of your pages.

As an example of the use of the history object, you will now create a script that displays Back and Forward buttons and uses these methods to navigate the browser.

You will use graphic images for the Back and Forward buttons. You can use the images from this book's Web site or make your own images to match the other graphics on your page.

TIP

Visit this book's Web site to download the listings for this hour and the graphics for the Back and Forward buttons: http://www.jsworkshop.com/.

Here's the part of the script that will handle the Back button:

<a HREF="javascript:history.back();">
 <img BORDER = 0 SRC="left.gif">
</a>

This uses a javascript: URL to execute a command when the user clicks on a link. In this case, the link is the left-arrow image. The script for the Forward button is nearly identical:

<a HREF="javascript:history.forward();">
 <img BORDER = 0 SRC="right.gif">
</a>

With these out of the way, you just need to build the rest of an HTML document. Listing 9.2 shows the complete HTML document, and Figure 9.2 shows a browser's display of the document. After you load this document into a browser, visit other URLs and make sure the Back and Forward buttons work.

Listing 9.2 A Web page that uses JavaScript to include Back and Forward buttons

<html>
<head><title>Graphic Back and Forward Buttons</title>
</head>
<body>
<h1>Graphical Back and Forward Buttons</h1>
<hr>
<p>This page allows you to go back or forward to pages in the history list.
These should be equivalent to the back and forward arrow buttons in the
browser's toolbar.</p>
<hr>
<a HREF="javascript:history.back();">
 <IMG BORDER = 0 SRC="left.gif">
</a>
<a HREF="javascript:history.forward();">
 <IMG BORDER = 0 SRC="right.gif">
</a>
<hr>
</body>
</html>

Figure 9.2. The Back and Forward buttons in Internet Explorer.

TIP

This script is an example of how much JavaScript can do with very little scripting. In fact, Listing 9.2 doesn't use any <script> tags at all, and only two JavaScript commands.

  • + Share This
  • 🔖 Save To Your Account