Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

74
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda