Whenever we want to go to another page we use anchor tag but when we have to redirect from one page to another page what can we do. Nothing to worry. In javascript, there are many solutions available. By the help of the javascript we can redirect to another page or if you want to wait for some time and then redirect to another page this feature is also available. So without wasting our let's see the example and codes how can we do it:---
--- Quick View ---
// Sets the new location of the current window.
window.location = "https://www.example.com";
// Sets the new href (URL) for the current window.
window.location.href = "https://www.example.com";
// Assigns a new URL to the current window.
window.location.assign("https://www.example.com");
// Replaces the location of the current window with the new one.
window.location.replace("https://www.example.com");
// Sets the location of the current window itself.
self.location = "https://www.example.com";
// Sets the location of the topmost window of the current window.
top.location = "https://www.example.com";
//redirect after some time
setTimeout(function() { window.location.href = "https://www.example.com"; }, 3000);
--- Video View ---
--- Detail View ---
All of the above code does the same job but they are slightly different in their uses. For example, if you use top.location redirect within an iframe, it will force the main window to be redirected. Another point to keep in mind is that location.replace() replaces the current document by moving it from the history, hence making it unavailable via the Back button of the browser.
For better approach and only to use for cross-browser compliant use this code:--
// Copy and paste the code in your project. Note :- Replace your url with "https://www.example.com"
Now if You want to redirect your page from one page to another page after hold for some time and wants to some message to the user. For example, if some operation is done by the user then you want to show the option to revert back in 10 sec if this action is done by mistake, the user will revert back if it done some mistake or wait for some 10 sec or decided second to lock the action. In that situation, you have to use this code. So let's see how we can do this:'--
// Copy and paste the code in your project. Note :- Replace your url with "https://www.example.com"
This code will redirect to another page for here https://www.example.com after 3 sec. Note you must have to pass the value in the millisecond.
You can also redirect after clicking on the button or on some condition. For this, you can use this code:-
// onclick event is assigned to the #button element.
document.getElementById("button").onclick = function() {
window.location.href = "https://www.example.com";
};
Course reference - https://appendto.com/2016/04/javascript-redirect-how-to-redirect-a-web-page-with-javascript/