You can use the ‘window.location
‘ object to redirect the user to a different page. Here is an example of how to do this using pure JavaScript:
function redirectToPage(url) {
window.location.href = url;
}
You can then call this function with the URL of the page you want to redirect the user to, like this:
redirectToPage('https://www.example.com');
Here is an example of how to do this using jQuery:
function redirectToPage(url) {
$(location).attr('href', url);
}
You can then call this function in the same way as the pure JavaScript example above.
Alternatively, you can use the ‘window.location.replace
‘ function to replace the current page with the new page, rather than adding the new page to the browser’s history. This can be useful if you don’t want the user to be able to use the browser’s back button to navigate back to the original page. Here is an example of how to use ‘window.location.replace
‘:
window.location.replace('https://www.example.com');
Note that this will not work if the user has disabled JavaScript in their browser. If you need to support users with JavaScript disabled, you can use a regular HTML ‘a
‘ element with the ‘href
‘ attribute set to the URL of the page you want to redirect.
ALSO SEE: How to empty an array in JavaScript? [Multiple ways]