- Refresher on the Different Types of Scripting
- Displaying Random Content on the Client Side
- Understanding the Document Object Model
- Using window Objects
- Working with the document Object
- Accessing Browser History
- Working with the location Object
- More About the DOM Structure
- Working with DOM Nodes
- Creating Positionable Elements (Layers)
- Hiding and Showing Objects
- Modifying Text Within a Page
- Adding Text to a Page
- Changing Images Based on User Interaction
- Thinking Ahead to Developing HTML5 Applications
- Summary
- Q & A
- Workshop
Working with the location Object
Another child of the window object is the location object. This object stores information about the current URL loaded in the browser window. For example, the following JavaScript statement loads a URL into the current window by assigning a value to the href property of this object:
window.location.href="http://www.google.com";
The href property contains the entire URL of the window’s current location. Using JavaScript, you can access portions of the URL through various properties of the location object. To understand these properties a bit better, consider the following URL:
http://www.google.com:80/search?q=javascript
The following properties represent parts of the URL:
location.protocol is the protocol part of the URL (http in the example).
location.hostname is the hostname of the URL (www.google.com in the example).
location.port is the port number of the URL (80 in the example).
location.pathname is the filename part of the URL (search in the example).
location.search is the query portion of the URL, if any (q=javascript in the example).
Unused in this example but also accessible are the following:
location.host is the hostname of the URL plus the port number (www.google.com:80 in the example).
location.hash is the anchor name used in the URL, if any.
The link object, introduced earlier in this chapter, also uses this list of properties for accessing portions of the URL found in the link object.
The location object has three methods:
location.assign() loads a new document when used as follows:
location.assign("http://www.google.com")
location.reload() reloads the current document. This is the same as using the Reload button on the browser’s toolbar. If you optionally include the true parameter when calling this method, it will ignore the browser’s cache and force a reload whether the document has changed or not.
location.replace() replaces the current location with a new one. This is similar to setting the location object’s properties yourself. The difference is that the replace method does not affect the browser’s history. In other words, the Back button can’t be used to go to the preceding location. This is useful for splash screens or temporary pages that it would be useless to return to.