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
You can try this without declaring the authenticate function:
EDIT:
Or, if you want to use the function style:
Or, even better as suggested in the comments, using event listener:
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.