So I'm trying to create a button that when pressed changes the content of an html page and updates the button to change its next function. However, whenever I use .onclick I end up printing the "2" to the console while still on the first press of the button. I've tried using .click as well, and the only thing that I can find that works is setting the function directly, however this is untidy and long. I wondered if there was another way to do this with cleaner code.
html:
<!DOCTYPE html>
<html lang="en-US">
<body>
<script src="Path_To_File"></script>
<p id="text">
<!-- text here -->
</p>
<button id="b1" type="button" onclick="pageFlip(1)">Button</button>
</body>
</html>
JS:
function pageFlip(page) {
var p = document.getElementById("text");
var b1 = document.getElementById("b1");
var b2 = document.getElementById("b2");
switch (page) {
case 1:
p.innerHTML = "newText";
b1.innerHTML = "newText";
b1.onclick = pageFlip(2);
break;
case 2:
console.log("2");
break;
}
}
What works:
b1.onclick = function changeButton() {
pageFlip(2)
}