Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda