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

75
Views
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 answers
Answer question

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 Report
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!