Redirect routes in HTML using Javascript

Tags: , , ,



I have 3 html files that I want to link together. The three files are button.html, option1.html, option2.html and all three files are stored in one src folder.

The button.html is a simple webpage that contains two buttons:

<!DOCTYPE html>
<html>
<head>
      <title>Page Title</title>
      <script type="text/javascript">
        document.getElementById("option1").onclick = function () {
            location.href = "./option1.html";
        };
        document.getElementById("option2").onclick = function () {
            location.href = "./option2.html";
        };
    </script>
</head>
<body>

      <button type="button" id="option1">Option 1</button>
      <button type="button" id="option2">Option 2</button>

</body>
</html>

and the two other .HTML file are regular pages each w/ different content.

<!DOCTYPE html>
<html>
<head>
<title>Option 1/2</title>
</head>
<body>

  // different data contained for option1.html and option2.html
  <h1>Heading for Option 1 or 2</h1>
  <p>Paragraph for Option 1 or 2</p>

</body>
</html>

I’m not sure what I’m doing wrong but even with the onClick() functions for each buttons, the buttons won’t link to the other HTML files. I’m wondering if I should have some kind of link tag in the header for the two HTML files. Also, I’m not very certain about that location.href line does in the script tag of button.html file. I just found some resources online to try this out.

Also, I need to do this using ONLY Vanila Javascript, HTML and CSS.

Please help me out. Thanks!!

Answer

UPDATED : This will work, I believe. See, first of all, always add your script tag just before the closing body tag. The reason is because that, the code will not work in case the DOM elements it looking for would not have been rendered.

<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>

  <button type="button" id="option1">Option 1</button>
  <button type="button" id="option2">Option 2</button>

  <script type="text/javascript">
    document.getElementById("option1").onclick = function() {
      location.href = "./option1.html";
    };
    document.getElementById("option2").onclick = function() {
      location.href = "./option2.html";
    };
  </script>

</body>

</html>


Source: stackoverflow