Javascript location.href Example
In these example we’re going to discuss and learn about the location.href
property. Let’s dive right in!
Definition and syntax
The location.href
property is a read-only one, that returns the URL of the current page, or sets one in case it’s modified.It’s syntax goes like below:
var x = location.href;
It will return the URL of the current page, in our case being http://www.webcodegeeks.com/web-development/javascript-loc…n-href-example/
.
Often, only location
is written in order to get the same result. That would not be wrong, as the location
object is part of the window
object, and contains every information about the URL. Moreover, we can use a number of methods on this object, where among the most popular are assign()
, replace()
and reload()
.
However, the catch is that while location
is an object, href
is merely one of it’s properties. Some other properties of this object are host
, hostname
, port
, and protocol
(which, amusingly can all be accessed at the same time through the property origin
). Also search
and protocol
are another couple of honorable mentions.
Usage
Let’s see which are the most common usages of the property.
Redirecting
It can be used to redirect to another page using the code snippet below:
location.href = "http://www.webcodegeeks.com/javascript/javascript-parseintstring-int-example/";
In this case we will be redirected to the URL specified by the property.
We explained above how to do redirection using location.href
, which would have the same effect as using location.assign(URL)
. Another very typical examples are:
Forced reloading
You can force the server to reload the current page using the code like below:
location.href.reload(true);
This property is more often than not used with functions like alert()
or search()
.
Comparing internal and external links
If you need to find out whether a link is internal or external, you can use href
to do it, using the code snippet below:
$$('a[href^="http://"]').each(function(a) { if(!a.get('href').contains(window.location.host)) { alert("The link is external"); } });
First, you grab all complete linked anchors and if they’re not on the domain of the current page, then an alert is put out, saying that the link is external.
Whichever way you use location.href
, you’re sure to have a good time coding as it’s quite simple to use.
Download the source code
This was an example of location.href in Javascript.
Download the source code for this tutorial:
You can download the full source code of this example here : locationHref