BeWebmaster

Javascript location Object explained

Ad

Javascript scripts can manipulate the Web pages and it's contents using a hierarchy of parent and child objects called the DOM (Document Object Model).Those objects are organized into a tree-like structure and represent all of the components of a web page. Objects in the DOM have properties, which describe the Web page, and methods, which allow you to work with parts of the Web page.The window object is the parent object for all the objects. One of the objects under window is the location object.

Location Object

Location object stores information about the current URL in the window. For example a statement:

window.location.href = "http://www.bewebmaster.com"; loads BeWebmaster website in the current browser window. The href property contains the entire URL, but you can use various properties to access portions of the URL.

Properties

Let's take following URL apart: http://www.bewebmaster.com:80/55.php?id=12#headline

  • location.protocol would give us the protocol part of the URL (http: )
  • location.hostname would give us host name of the URL (i.e. www.bewebmaster.com)
  • location.port would give us the port number of the URL (80)
  • location.pathname would give us the filename part of the URL (55.php)
  • location.search would give us the query part (if any) of the URL (id=12)
  • location.hash would give us the anchor name used in the URL (#headline)

Methods

The location object has two methods:

location.reload()- reloads the current page. It acts the same as the browser reload button. You can include a parameter true to 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. It's pretty much the same as changing the location properties, except that it doesn't affect the browser's history. So, if you use replace method you can't use browser's back button to go to previous location. This is mostly used for temporary pages or splash screens.

Example

Let's say you are using an AJAX script to load a page based on the search query in the URL. You could create a function:

function getSearch()
{
    return document.location.search;
}

or just use

document.location.search somewhere within the function that handles AJAX calls.

If you want to pass a url to the function above you can modify above code to.

function getSearch(url)
{
    return url.location.search;
}

and call it like this:

<a href="javascript:getSearch(this.document);">Pass a URL</a>

There you have it a quick overview of the DOM's location object. Feel free to add any comments.