How to redirect in JavaScript

The window.location is an object that can be used to redirect from one page to another in a browser. We sometimes need to redirect users from current page to another (same website or some other website) upon clicking a link or pressing a button or as a session expires etc.

In this tutorial, we will explain how to use JavaScript window.location with examples.

Syntax to redirect by using window.location

Following is the way to use JS redirect:

window.location = “http://www.example.com/”;

Now let us show you examples of JavaScript redirect by using window.location.

A redirect example

Following is redirect example where we will redirect a web page to google.com by using JavaScript window.location, as you click on the button.

Experience this example online

In the demo, when you click on the button, the function will be called at the onclick event and the page will be redirected to another URL.

redirect URL example with time delay

You can code in JavaScript to delay a redirection. This may be useful in situations where you want to show a notification to the user before a session ends or showing a message that you will be redirected to another page, for example, in ten seconds.

Following is an example of redirect URL with a delay of five seconds as you click on the button. See the working example online by clicking the link below:

Experience this example online

We have two JS functions. As you click on the button “Redirect with five seconds delay” the delayredir function is called which is placed at the onclick event of the button.

This function uses the setTimeout function that delays redirection by five seconds and calls another function redirURL that redirects to a given URL by using the window.location JavaScript method.

Using document.location example

You can use document.location instead of window.location to redirect to another web page. See the following example of using JS document.location below.

Experience this example online

You can see the page is redirected by using document.location.

Also see: Javascript innerHTML property