There are several ways to redirect users:
- If you want to simulate someone clicking on a link, update the
window.location.href
property
- If you want to simulate a HTTP redirect, use the
window.location.replace()
function
Create your buttons:
<button id="my-button-1">Redirect 1</button>
<button id="my-button-2">Redirect 2</button>
Then, instead of using inline events, use event listeners in order to allow event delegation:
document.getElementById("my-button-1").addEventListener("click", function() {
window.location.replace("redirect/path/for/btn-1.html");
});
document.getElementById("my-button-2").addEventListener("click", function() {
window.location.replace("redirect/path/for/btn-2.html");
});
If you want to simulate a link click, use this instead:
document.getElementById("my-button-1").addEventListener("click", function() {
window.location.href = "redirect/path/for/btn-1.html";
});
document.getElementById("my-button-2").addEventListener("click", function() {
window.location.href = "redirect/path/for/btn-2.html";
});
NOTE: The window.location.replace(...)
doesn't keep the originating page in the session history, this means that user won't have to click the back button to get back to where they were.