The DOM Location Object Properties - Hash It Up
(Page 2 of 6 )
As stated in our table above, hash is used to retrieve or set a URL, starting from the hash (#) symbol. If you are up to par on your HTML (and if you are reading this I assume that you are), then you will know that the hash (#) symbol is used for an anchor in a URL. Below, we are going to write some code to retrieve the URL after a hash symbol. For this example we will say that we have a page URL of http://www.devshed.com/example.html#testing.
<html>
<body>
<script type="text/javascript">
document.write(location.hash);
</script>
</body>
</html>
Here, the result would be:
#testing
If we wanted to set the URL after the hash, we would do so in this manner:
<html>
<body>
<script type="text/javascript">
location.hash="#chickenhawk";
document.write(location.hash);
</script>
</body>
</html>
Here, the URL after the hash would be chickenhawk.
Let's say that we wanted to make hash a little more complicated. In the following example, we will create two pages. One page will contain some bulleted lists with anchors. The second page will contain buttons that will link to the locations on our first page. Here is the page of lists and anchors, which we will name Chinese.htm:
<html>
<body>
<a name="Chicken">Chicken</a>
<ul>
<li>Fried</li>
<li>Wings</li>
<li>Orange</li>
</ul>
<a name="Appetizers">Appetizers</a>
<ul>
<li>Crab Rangoon</li>
<li>Fried Dumplings</li>
<li>Egg Rolls</li>
</ul>
<a name="Rice">Rice</a>
<ul>
<li>White</li>
<li>Chicken Fried</li>
</ul>
</body>
</html>
As you can see, we have three anchors: Chicken, Appetizer, and Rice. Each anchor links to a section about different sorts of food. In this instance, Chicken links to a section discussing fried, orange, and wings. Rice links to White and Chicken Fried, etc.
Next we will create the second page, which has links to the various anchors in our first page:
<html>
<head>
<script type="text/javascript">
function linker(y)
{
var x=window.open("chinese.htm","","width=500,height=400");
x.location.hash=y;
}
</script>
</head>
<body>
<h3>Chinese Anchors</h3>
<p>Click a button to view the anchor and its list:</p>
<input type="button" value="Chicken" onclick="linker(Chicken)">
<input type="button" value="Appetizer" onclick="linker(Appetizer)">
<input type="button" value="Rice" onclick="linker(Rice)">
</body>
</html>
When you test the page, if you click on the Chicken button, you should see something along the lines of this:
Chicken
Next: Being a Good Host >>
More JavaScript Articles
More By James Payne