skip to Main Content

I am trying to make the navigation work on first click of the button. But for some reason the button won’t work on first click and works fine on second click

function authenticate() {
  let x = document.getElementById('aut').value;
  if (x == 'code') {
    document.getElementById('myButton').onclick = function() {
      window.location.href = 'https://www.google.com';
    };
  } else {
    alert('Please check your password')
  }
  console.log('If this message appears in the console, JavaScript is running.');
}
<div>
  <label for="auth">Password:</label>
  <input type="password" name="auth" id="aut">
  <button id="myButton" onclick="authenticate()">Authenticate</button>
</div>

2

Answers


  1. You can try this without declaring the authenticate function:

    document.getElementById("myButton").onclick = function () {
      let x = document.getElementById("aut").value;
    
      if (x == "code") {
        window.location.href = "https://www.google.com";
      } else {
        alert("Please check your password");
      }
      console.log("If this message appears in the console, JavaScript is running.");
    };
    

    EDIT:
    Or, if you want to use the function style:

    function authenticate() {
      let x = document.getElementById("aut").value;
    
      if (x == "code") {
        window.location.href = "https://www.google.com";
      } else {
        alert("Please check your password");
      }
      console.log("If this message appears in the console, JavaScript is running.");
    }
    

    Or, even better as suggested in the comments, using event listener:

    const myButton = document.getElementById("myButton");
    
    myButton.addEventListener("click", () => {
      let x = document.getElementById("aut").value;
    
      if (x == "code") {
        window.location.href = "https://www.google.com";
      } else {
        alert("Please check your password");
      }
      console.log("If this message appears in the console, JavaScript is running.");
    });
    
    
    Login or Signup to reply.
  2. On first click, you only changed the button’s onclick handler, not execute it.
    On second click, you executed the changed handler.
    It seems like you don’t need to change the handler, just execute it right away.

    function authenticate() {
      let x = document.getElementById('aut').value;
      if (x == 'code') {
        window.location.href = 'https://www.google.com';
      } else {
        alert('Please check your password')
      }
      console.log('If this message appears in the console, JavaScript is running.');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search