How to make a button redirect one page to another page with JavaScript?

Sometimes, we want to make a button redirect one page to another page with JavaScript.

In this article, we’ll look at how to make a button redirect one page to another page with JavaScript.

How to make a button redirect one page to another page with JavaScript?

To make a button redirect one page to another page with JavaScript, we can set location.href to the destination URL on click.

For instance, we write

<button id="myButton">Home</button>

to add a button.

Then we write

document.getElementById("myButton").onclick = () => {
  location.href = "www.yoursite.com";
};

to select the button with getElementById.

And then we set its onclick property to a function that sets location.href to the destination URL to go to the URL when we click the button.

Conclusion

To make a button redirect one page to another page with JavaScript, we can set location.href to the destination URL on click.