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

77
Vistas
Looping eventListener?

Hi you guys I'm new to JS and programming in general. Just started learning and was wondering out of curiosity is there a way to loop through click eventListener. So Each time I click on my h1 header with a title id I get the innerHTML changed kind of like a infinite shuffle ?

const element = document.getElementById("title");


element.addEventListener("click", function(){
    element.innerHTML = "Cool Right?";

    element.addEventListener("click", function(){
        element.innerHTML = "SoundPad";
    });
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. Create an array with the string you would like to cycle (strings)

  2. Create an integer in which we will hold the current shown index (i)

  3. Add click listener in which we will:

    1. Check if our current index is at the last value, if so, cycle to 0
    2. Set element.innerHTML to the index of the array
    3. Bump the index

const element = document.getElementById("title");
const strings = [ 'Hello', 'How', 'Are', 'You', '?' ];
let i = 0;

element.addEventListener("click", () => {
    if (i === strings.length) i = 0;
    element.innerHTML = strings[i];
    i++;
});
<h1 id='title'>Starting Title</h1>


Instead off the 3 lines, we can simplify this in many ways:

  1. Fancy one-liner using the same logic as above

    element.addEventListener("click", () => element.innerHTML = strings[(i === (strings.length - 1)) ? (i = 0) : ++i]);
    
  2. Using the modulo operator (%) to set i

    element.addEventListener("click", () => {
         i = (i + 1) % strings.length
         element.innerHTML = strings[i];
    });
    
about 4 years ago · Juan Pablo Isaza Denunciar
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