How to Switch Between HTML Pages Using JavaScript?

Estimated read time 1 min read

You can switch between HTML pages using JavaScript by setting the window.location.href property to the URL of the desired page. For example:

<button id="myButton">Go to Page 2</button>

<script>
  var button = document.getElementById("myButton");
  button.addEventListener("click", function() {
    window.location.href = "page2.html";
  });
</script>

This will navigate to the page with the URL “page2.html” when the button is clicked.

Another option is to use the window.open() method, which opens a new window or tab and loads the specified URL. For example:

<button id="myButton">Open Page 2 in a new window</button>

<script>
  var button = document.getElementById("myButton");
  button.addEventListener("click", function() {
    window.open("page2.html", "_blank");
  });
</script>

This will open the page with the URL “page2.html” in a new window or tab when the button is clicked.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply