How to make a redirect JavaScript
Learn how to do a JavaScript redirect with an example and understand how to implement a redirect to a different URL.
Creating a Redirect Using JavaScript
You can create a redirect using JavaScript by using the window.location object. This object can be used to get the current page address (URL) and redirect the browser to a new page. It's a great way to create a simple and effective redirect without having to use a server-side language such as PHP.
The following code example shows how to create a redirect using JavaScript:
// Get the current page address (URL)
var currentURL = window.location.href;
// Redirect the browser to a new page
window.location.href = "http://www.example.com";
In this example, we are first getting the current page address (URL) and then redirecting the browser to a new page. We can also set the URL of the new page to a variable, such as the following:
// Get the current page address (URL)
var currentURL = window.location.href;
// Set the URL of the new page
var newURL = "http://www.example.com";
// Redirect the browser to a new page
window.location.href = newURL;
The above example is useful if you want to dynamically set the URL of the page you want to redirect to. You can also set a delay before the redirect takes place, as shown here:
// Get the current page address (URL)
var currentURL = window.location.href;
// Set the URL of the new page
var newURL = "http://www.example.com";
// Set a 5 second delay before the redirect takes place
setTimeout(function(){
window.location.href = newURL;
}, 5000);
In this example, we are setting a 5 second delay before the redirect takes place. This can be useful if you want to give the user a chance to read a message or take an action before the redirect occurs.
Creating a redirect using JavaScript is a simple and effective way to redirect the user to a different page. It can be used to create a redirect without having to use a server-side language such as PHP.