Question

How to Redirect to Another Webpage in JavaScript

javascriptjqueryhttp-redirect

Question

How can I redirect a user from one page to another using jQuery or plain JavaScript?

Short Answer

By the end of this page, you will understand how browser redirects work in JavaScript, how to send a user to a new URL, when to use window.location.href versus window.location.replace(), and why jQuery is usually not needed for redirects.

Concept

Redirecting means telling the browser to load a different URL.

In web development, this is commonly done after an action such as:

  • submitting a form
  • logging in successfully
  • logging out
  • clicking a button
  • checking whether a user has permission to view a page

In JavaScript, redirects are usually handled through the browser's window.location object. This object represents the current page URL and gives you ways to change it.

The most common redirect approaches are:

  • window.location.href = "https://example.com" — sends the user to a new page
  • window.location.assign("https://example.com") — also sends the user to a new page
  • window.location.replace("https://example.com") — sends the user to a new page without keeping the current page in browser history

This matters because browser history affects the Back button:

  • with href or assign(), the user can usually click Back to return
  • with replace(), the current page is replaced, so Back usually will not return to it

Although the question mentions jQuery, jQuery does not provide a special redirect feature. In practice, developers use normal JavaScript even inside jQuery event handlers.

Example:

$("#goButton").on("click", function () {
  window.location.href = "/dashboard";
});

So the core concept is not really a jQuery feature. It is a browser navigation feature provided by JavaScript.

Mental Model

Think of window.location as the browser's address bar.

  • Reading it is like looking at the current address.
  • Changing it is like typing a new address and pressing Enter.
  • Using replace() is like swapping the current history entry instead of adding a new one.

So if you write:

window.location.href = "/home";

you are effectively telling the browser: "Go to this address now."

Take Quiz

Syntax and Examples

Basic redirect syntax

window.location.href = "https://example.com";

This loads the new page and keeps the current page in browser history.

Using assign()

window.location.assign("https://example.com");

This behaves similarly to href.

Using replace()

window.location.replace("https://example.com");

This redirects without leaving the current page in the browser history.

Redirect to another page on the same site

window.location.href = "/profile";

This is common for internal navigation.

Redirect after a button click

const button = document.getElementById("goButton");

button.addEventListener("click", function () {
  window.location.href = "/dashboard";
});

When the user clicks the button, the browser loads /dashboard.

Redirect with jQuery event handling

$("#goButton").on("click", function () {
  window.location.href = "/dashboard";
});

jQuery is only being used to listen for the click. The redirect itself is still standard JavaScript.

Delayed redirect

setTimeout(function () {
  window.location.href = "/thank-you";
}, 2000);

This waits 2 seconds, then redirects.

Step by Step Execution

Consider this example:

const isLoggedIn = true;

if (isLoggedIn) {
  window.location.href = "/dashboard";
}

Step by step:

  1. isLoggedIn is created and set to true.
  2. The if statement checks whether isLoggedIn is truthy.
  3. Because the value is true, the code inside the block runs.
  4. window.location.href is assigned the value "/dashboard".
  5. The browser starts navigating to /dashboard.
  6. The current page stops being the active page once navigation completes.

Now compare this version:

const isLoggedIn = true;

if (isLoggedIn) {
  window.location.replace("/dashboard");
}

The early steps are the same, but the history behavior changes:

  1. The condition is checked.
  2. The redirect happens.
  3. The current page is replaced in browser history.
  4. The Back button usually will not return the user to the original page.

Real World Use Cases

Redirects are used in many practical situations:

  • Login flow: after successful authentication, send the user to /dashboard
  • Logout flow: after clearing session data, send the user to /login
  • Protected pages: if a user is not authorized, redirect to /unauthorized or /login
  • Form submission: after saving data, redirect to a confirmation page
  • Moved content: send users from an old route to a new route
  • Language or region handling: redirect users to /en, /fr, or region-specific pages
  • Checkout flow: move users to payment, confirmation, or order summary pages

Example of redirecting unauthenticated users:

if (!userIsAuthenticated) {
  window.location.replace("/login");
}

This is common because you may not want users to go Back to a protected page.

Take Quiz

Real Codebase Usage

In real projects, redirects are often combined with application logic rather than written by themselves.

Guard clauses

A common pattern is checking a condition early and redirecting immediately.

if (!token) {
  window.location.replace("/login");
  return;
}

This avoids deeply nested code.

After validation or success

if (formIsValid) {
  saveData();
  window.location.href = "/success";
}

Error handling flows

if (response.status === 401) {
  window.location.replace("/login");
}

Redirect after async work

fetch("/api/logout", { method: "POST" })
  .then(() => {
    window.location.href = "/login";
  });

Using relative vs absolute URLs

Developers often prefer relative URLs for internal navigation:

window.location.href = "/settings";

And absolute URLs for external navigation:

window.location.href = "https://partner.example.com";

Important note

In larger applications, especially single-page apps, navigation may be handled by a router instead of direct browser redirects. But for normal browser navigation, window.location remains the standard tool.

Common Mistakes

1. Thinking jQuery has a special redirect method

jQuery does not have a built-in redirect API.

// Not a real jQuery redirect method
$.redirect("/home");

Use standard JavaScript instead:

window.location.href = "/home";

2. Forgetting the difference between href and replace()

If you want the user to be able to go back, use href or assign(). If you do not want that, use replace().

window.location.replace("/login");

3. Using an invalid or incomplete URL accidentally

Broken:

window.location.href = "example.com";

This may be treated as a relative path instead of a full website URL.

Better:

window.location.href = "https://example.com";

4. Expecting code after redirect to reliably finish

Broken idea:

window.location.href = "/next";
console.log("This may not matter because navigation starts immediately");

Once navigation begins, the page is leaving. Do not rely on later code to complete important work.

5. Redirect loops

If page A redirects to page B, and page B redirects back to page A, the user can get stuck.

Always check your conditions carefully.

6. Using JavaScript redirect when a server redirect is better

If a page should always redirect, a server-side redirect is often cleaner and faster. JavaScript redirects happen only after the page loads.

Comparisons

ApproachExampleKeeps current page in history?Common use
window.location.href = urlwindow.location.href = "/home"YesStandard redirect
window.location.assign(url)window.location.assign("/home")YesExplicit navigation method
window.location.replace(url)window.location.replace("/home")NoLogin/logout/protected pages

jQuery vs plain JavaScript

OptionPurposeNotes
jQueryEvent handling, DOM helpersDoes not provide the actual redirect feature
Plain JavaScriptBrowser navigationStandard way to redirect

Client-side redirect vs server-side redirect

TypeWhen it happensBest for
Client-side redirectAfter page JavaScript runsUI-driven flows, button clicks, post-action navigation
Server-side redirectBefore page is shown to the userPermanent route changes, auth protection, SEO-sensitive redirects
Take Quiz

Cheat Sheet

// Standard redirect
window.location.href = "/home";

// Equivalent redirect method
window.location.assign("/home");

// Redirect without keeping current page in history
window.location.replace("/home");

// Delayed redirect
setTimeout(() => {
  window.location.href = "/home";
}, 1000);

Quick rules

  • Use window.location.href for most redirects.
  • Use window.location.replace() when the user should not return to the previous page with Back.
  • jQuery is not needed for redirecting.
  • Use relative URLs like /dashboard for internal pages.
  • Use full URLs like https://example.com for external sites.
  • Be careful with redirect loops.
  • Prefer server-side redirects when the page should always redirect.

Useful reminder

window.location represents the current browser URL. Changing it tells the browser to navigate somewhere else.

FAQ

How do I redirect to another page in JavaScript?

Use:

window.location.href = "/new-page";

How do I redirect without allowing the user to go back?

Use:

window.location.replace("/new-page");

Is there a jQuery function for redirects?

No. jQuery does not provide a special redirect method. Use window.location.

What is the difference between href and replace()?

href keeps the current page in browser history. replace() removes it from history.

Can I redirect after a delay?

Yes:

setTimeout(() => {
  window.location.href = "/next";
}, 2000);

Should I use JavaScript or a server redirect?

If the redirect should always happen, server-side is often better. If it depends on user interaction in the browser, JavaScript is appropriate.

Take Quiz

Mini Project

Description

Build a small login-check page that redirects users based on whether they are signed in. This demonstrates conditional redirects, button-triggered redirects, and the difference between normal navigation and history-replacing navigation.

Goal

Create a page that sends signed-in users to a dashboard and signed-out users to a login page.

Requirements

  • Create a boolean variable representing whether the user is logged in.
  • If the user is logged in, redirect to /dashboard.
  • If the user is not logged in, redirect to /login.
  • Use replace() for the login redirect.
  • Add a button that redirects to a help page when clicked.
Take Quiz

Keep learning

Related questions

View more