How to Navigate to Another Page in JavaScript
In this article, we will explore two methods to achieve the task of clicking a button and navigating to another HTML page using JavaScript.
Method 1: Using the Window.location Object #
One straightforward way to redirect to another HTML page is by using the window.location object. This method involves changing the href property of the location object to the URL of the desired page when the button is clicked.
Explanation :
- The HTML button element is assigned an ID of navigateBtn.
- The JavaScript code within the <script> tag targets the button by its ID and attaches an event listener to it.
- When the button is clicked, the event listener is triggered, and the window.location.href property is modified to the URL of /p/example.html.
Method 2: Using the Location.assign() Method #
An alternative method is to utilize the Location.assign() method. This method works similarly to the previous approach but offers a more explicit way to redirect to another page.
Explanation :
- The HTML and JavaScript structure in this method is similar to the previous one.
- The difference lies in using the location.assign() method directly, passing the target URL as its argument.
- Upon clicking the button, the location.assign() method triggers, directing the browser to navigate to the specified HTML page.
Conclusion : #
In this article, we explored two approaches for navigating to another HTML page using JavaScript.
The first method involves manipulating the window.location object's href property, while the second method utilizes the Location.assign() method.