• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / Using Javascript’s Location Object to Work with URLs

Using Javascript’s Location Object to Work with URLs

28 July 2008 / 2 Comments

JavaScript gives you many ways to access and change the current URL that is displayed in the visitor’s browser. All these techniques use the Location object, which is itself a property of the Window object. You can create a new Location object that contains the current URL as follows:


var currentURL = window.location;

In this tutorial, you explore all the properties and methods of the Location object. You learn:

  • How to read all the different parts of a URL
  • How to send the visitor to another page by changing the URL, and
  • How to automatically reload or refresh the page.

The anatomy of a URL

A URL can be broken down into as many as six components, though many of them are optional:


<protocol>//<hostname>:<port>/<pathname><search><hash>
The only required components of a URL are the protocol and the hostname; all other components are optional.

Here’s an example of a URL with all these components:


http://www.example.com:80/example.cgi?x=3&y=4#results

In this example, http: is the protocol, www.example.com is the hostname, 80 is the port, /example.cgi is the pathname, ?x=3&y=4 is the search, or query string, and #results is the hash, or the anchor to display within the page.

Reading the current URL through the Location object

You can access all of these URL components using Location properties of the same names. You can also access the following properties:

host
Contains the hostname and the port combined into one string, e.g. www.example.com:80
href
Contains the complete URL, e.g. http://www.example.com:80/example.cgi?x=3&y=4#results

Here are some examples (assume that the example URL above is displayed in the browser’s address bar at the time the code below is run):


var currentURL = window.location;
alert ( currentURL.href );     // Displays 'http://www.example.com:80/example.cgi?x=3&y=4#results'
alert ( currentURL.protocol ); // Displays 'http:'
alert ( currentURL.host );     // Displays 'www.example.com:80'
alert ( currentURL.hostname ); // Displays 'www.example.com'
alert ( currentURL.port );     // Displays '80'
alert ( currentURL.pathname ); // Displays '/example.cgi'
alert ( currentURL.search );   // Displays '?x=3&y=4'
alert ( currentURL.hash );     // Displays '#results'

Manipulating the URL using the Location object

You can use the href property of the Location object to send visitors to a completely different page:


window.location.href = "http://www.example.com/anotherpage.html";

Here’s a simple example:


<input type="button" onclick="window.location.href='http://www.google.com/'" value="Visit www.google.com" />

Here’s the resulting button. Click it to visit www.google.com if you like, then close the window to return here.

Setting the Location.href property like this keeps the previous URL in the browser’s history, so the visitor can click the Back button to return to the previous page. If you don’t want the visitor to be able to go back to the previous URL, use Location.replace() instead:


window.location.replace ( "http://www.example.com/anotherpage.html" );

This loads the new URL, and also replaces the current history entry with the new URL, so that the previous URL is effectively wiped from the history.

As well as redirecting the browser to a different URL, you can selectively change parts of the current URL using the Location object properties. For example, to change the URL’s hash to a different anchor within the page:


window.location.hash = "#moreResults";

Here’s an example:


<input type="button" onclick="window.location.hash='#top'" value="Jump to the top of the page" />

…and here’s the resulting button (scroll to the bottom of the page to see it). Click it, and your browser moves to the top of the page. That’s because the page contains an anchor named #top at the top. Notice how the URL changes in the browser’s address bar. (You can close the window afterwards to return here.)

Reloading the page

Finally, you can use the Location.reload() method to force the browser to reload the current URL, just as if the visitor had clicked their Reload/Refresh button:


window.location.reload ( );

To force the browser to retrieve the page directly from the server, bypassing any caches, pass a true parameter to Location.reload():


window.location.reload ( true );

Here’s an example that uses Location.reload() to create a button to refresh the page:


<input type="button" onclick="window.location.reload()" value="Reload the page" />

Here’s the button — click it to see it in action!

Summary

You’ve now explored all the properties and methods of JavaScript’s Location object. This object is useful for:

  • Reading the current URL — for example, to see what query parameters have been included in the URL. Good if you’re creating dynamic JavaScript pages.
  • Changing the current URL — so you can move to a different point in the page, or send visitors off to a different page. This allows you to do things like JavaScript drop-down menus for navigation.
  • Reloading the current page — either in response to a button click, or automatically. For example, you can use Location.reload() with setTimeout() or setInterval() to reload the page periodically.

Filed Under: JavaScript Tagged With: address, alter URL, hash, host, hostname, href. protocol, pathname, port, redirect, search, URI, window.location

Reader Interactions

Comments

  1. valestudios says

    8 February 2012 at 8:52 pm

    Hi, thanks for the article. Is there any way to essentially combine the replace and reload functions? I need to force the page to reload and land on a specific anchor tag.

    Reply
  2. matt says

    15 February 2012 at 2:57 am

    @valestudios: Could you not just use replace() to set the new URL (with your anchor hash appended), then call reload() straight afterwards to reload the entire page?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits