Javascript window.location to redirect with demo

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 in javascript

Following is the way to use JS redirect:

window.location = “”;

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

A redirect example

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

Experience this example online

As you can see when you click on the button “Click here to see Javascript Redirect” the function will be called at 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 user with the notification 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

As you can 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 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

Was this article helpful?

Related Articles

Leave A Comment?