How to Redirect a User to Another URL with Javascript



Javascript


In this article, we show how to redirect a user to another URL with Javascript.

If you know server-side languages, such as PHP and Python, they can easily be used to redirect a user to another web page. However, a front-end, client-side language, such as Javascript, can perform the same action very easily.

Javascript can do this using the window object.

Upon the window object, there is an attribute called location. Location is referencing the URL of the page.

So if we change the location attribute of the window object, then we can change which URL the window object renders.

We can do this either by changing the href attribute of the location attribute or by using the assign() or replace() function.

As a demonstration, click on the button below to go to the google website.



In the following code below, we show 3 ways to redirect to a URL with Javascript.



So above is 3 ways to perform a page redirect in Javascript.

The first solution is by changing the href attribute of the location attribute of the window object. By changing this href attribute, it's simulates how you create an anchor tag and set the href to something, and the user clicks it.

The second solution uses the Javascript assign() function. The assign() function is a function that allows us to load a new document into the window object. So we load in the google URL with the assign() function.

The third solution uses the Javascript replace() function. The replace() funtion is a function that allows us to replace the current URL of the window object with the new one we specify, which in this case is the google home page URL.

The difference between using the Javascript assign() function and the Javascript replace() function is that the replace() function removes the URL from the current document from the document history; this means that a user cannot hit the 'back' button to navigate back to the previous document (which the user got redirected from). So you would use the assign() function if you want to give the user the ability to go back to the previous page. The href method, too, allows a user to go back to a previous page.

So this is how to redirect a user to another URL with Javascript.


Related Resources

How to Hide an HTML Element with jQuery

How to Show an HTML Element with jQuery

How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery

How to Upload a File with the Click of an Image with jQuery



HTML Comment Box is loading comments...