Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Setting button.onclick via button click activates on first button press

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)
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!