How do I redirect to another webpage in Javascript?
You can set window.location.href to redirect to another webpage. Set the location property to the URL of the page to which you want to visit.
Here's how to go about it:
// Redirect to another webpage
window.location.href = "https://www.example.com";
Replace "https://www.example.com" with the URL of the page to which you want to redirect. This line of code instructs the browser to load the provided URL, forwarding the user to that page.
If you wish to imitate a link click to initiate a redirect, use the following method:
// Simulate a click on a link to redirect
var link = document.createElement('a');
link.href = "https://www.example.com";
link.click();
This code generates an invisible link element, assigns the target URL to its href attribute, and then fires a click event on it. The user will be redirected to the selected webpage as well.
Practice More on: https://interviewplus.ai/developers-and-programmers/javascript/questions
Comments
Post a Comment