How can I redirect the user from one page to another using jQuery or pure JavaScript?

How can I redirect the user from one page to another using jQuery or pure JavaScript?

You can redirect the user from one page to another using either jQuery or pure JavaScript. Here are two examples:

Using jQuery:

// Redirect the user to the specified URL
$(location).attr('href', 'https://www.example.com');

// Redirect the user to the URL of the current page  
$(location).attr('href', window.location.href);

Using pure JavaScript:

// Redirect the user to the specified URL
window.location.href = 'https://www.example.com';

// Redirect the user to the URL of the current page
window.location.href = window.location.href;

Both examples use the href property of the location object to set the URL of the new page. In jQuery, you can use the attr method to set the href property, while in pure JavaScript you can assign the URL directly to the href property.

Note that when you redirect the user to a new page, any unsaved data on the current page will be lost, so it's a good idea to confirm with the user before redirecting them. You can do this using a JavaScript confirm dialog, like this:

if (confirm('Are you sure you want to leave this page?')) {
// Redirect the user to the specified URL window.location.href = 'https://www.example.com';
}

This will display a dialog box with a "OK" and "Cancel" button. If the user clicks "OK", they will be redirected to the specified URL. If they click "Cancel", the redirect will be canceled.



Back to The Programmer Blog