To redirect to another page in JavaScript when a user clicks on an element, you can use the onclick
event handler and the window.location
object.
Here’s an example of the syntax for redirecting to another page in JavaScript using the onclick
event handler:
element.onclick = function() {
window.location.href = "https://example.com/newpage";
};
When the element is clicked, the anonymous function assigned to onclick
is executed. Inside the function, we set window.location.href
to the desired URL, which causes the browser to navigate to the specified page.
Redirect to another page in JavaScript onclick example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>Redirect Example</title>
</head>
<body>
<button id="redirectButton">Click me to redirect</button>
<script>
// Get the button element
var button = document.getElementById('redirectButton');
// Attach onclick event handler
button.onclick = function() {
// Redirect to the desired page
window.location.href = "https://example.com/newpage";
};
</script>
</body>
</html>
Output:
Another example
<button id="myButton" class="float-left submit-button">Home</button>
<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "http://www.yoursite.com";
};
</script>
This code can be used to create a button on a webpage that, when clicked, navigates the user to the specified URL.
Do comment if you have any doubts or suggestions on this JS web page topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version