0

How to redirect a user to another page on a website using a linked JavaScript file, and how to convert the following line of code to non-embedded, linked JavaScript?

<button id="mybutton" type="button" onclick="myFunction()">Click me!</button> 

HTML:

<button id="mybutton" type="button">Click me!</button>

JavaScript:

function goToAnotherPage() {
  window.location.assign("myotherpage.html");
}

function init() {
  document.getElementById("mybutton").onclick = goToAnotherPage();
}
username653ue6
  • 31
  • 2
  • 10

1 Answers1

0

There are several ways to redirect users:

  1. If you want to simulate someone clicking on a link, update the window.location.href property
  2. 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.

Malekai
  • 4,765
  • 5
  • 25
  • 60
  • You mean **event listeners** in order to allow **event delegation**. It is fair to point this out so I don't know why this gets downvoted. Maybe add some HTML so your answer would be more clear. – Barrosy Apr 24 '19 at 14:54
  • @Barrosy Thanks for the heads up, I hadn't seen my mistake. – Malekai Apr 24 '19 at 14:57
  • You're very welcome, I wish you the best with your project. – Malekai Apr 24 '19 at 15:14