skip to Main Content

I’m trying to have a button change links when you click the buttons on the menu.

For example, I click button 1 and then I click the Link button it opens webpage 1, but then I click button 2 and then click the Link button, it is still webpage 1 that opens.

How do I make it to where it would change the links every time a button is pressed?

Here is what I had done so far, but after one button is clicked it doesn’t change the link again, even when clicking the other button.

my code is here:

HTML:

<nav class= "menu">
  <li id="button1" onclick="button1()"> Page 1</li>
  <li id="button2" onclick="button2()">Page 2</li>
</nav>

<div>
  <li id="Link" href="#">View Page</li>
</div>

Javascript:

const bttn = document.getElementById("Link");

function button1(){
  bttn.addEventListener('click', function bttn3() {
  var url = "webpage1.html";
  window.open(url);
}

function button2(){
  bttn.addEventListener('click', function bttn3() {
  var url = "webpage2.html";
  window.open(url);
}

2

Answers


  1. Your HTML has many errors…

    A simplest way is about using a data attribute

    const
      bttn    = document.querySelector('#Link')
    , menuElm = document.querySelector('menu')
      ;
    menuElm.addEventListener('click', e =>  // use event delegation
      {
      if (!e.target.matches('li[data-url]')) return
      
      bttn.dataset.url = e.target.dataset.url;
      bttn.textContent = e.target.textContent;
      })
    bttn.addEventListener('click', e =>
      {
      let url = `https://${bttn.dataset.url}`;
      // window.open( url );
      console.clear();
      console.log(`window.open( ${url} ) is not supported on SO snippet`);
      })
    li { cursor: pointer; }
    <menu> <!-- use menu element, nav element doesn't accept li -->
      <li data-url="developer.mozilla.org/en-US/docs/Web"> mozilla </li>
      <li data-url="stackoverflow.com/help/"> help !</li>
    </menu>
    
    <ol>  <!-- don't use div element, it doesn't accept li -->
      <li id="Link" dat-url="#">View Page</li>
    </ol>
    Login or Signup to reply.
  2. Note: Place JavaScript code after HTML code.

    var url = "";
    
    document.getElementById("Link").addEventListener('click', function(){
      //window.open(url);
      alert(url);
    });
    
    function button1(){
      url = "webpage1.html";
    }
    
    function button2(){
      url = "webpage2.html";
    }
    <nav class= "menu">
      <li id="button1" onclick="button1()"> Page 1</li>
      <li id="button2" onclick="button2()">Page 2</li>
    </nav>
    
    <div>
      <li id="Link" href="#">View Page</li>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search