Redirecting to another page with JavaScript & jQuery is easy. jQuery is not necessary, instead JavaScript’s built-in window.location
object should be used. There are two commonly used approaches, the window.location.replace()
method and the window.location.href
variable. Understanding the differences between the two is important.
HTTP Redirect
For a standard redirect, replace()
is usually the best approach.
window.location.replace("https://www.page.to/redirect/");
It’s better than using window.location.href = …
because replace()
skips the browser’s history. This ensures that users do not get stuck in a never-ending back-button redirect loop.
User Clicking a Link
window.location.href = "https://www.google.com";
This method mimics the events that occur when a user clicks a link.