Javascript location Object explained
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 this statement loads emirplicanic.com website in the current browser window.
window.location.href = "http://www.emirplicanic.com";
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.emirplicanic.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.emirplicanic.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 getSearch function modify the code like this:
function getSearch(url)
{
return url.location.search;
}
and call it like this:
Pass a URL
There you have it a quick overview of the DOM’s location object.
