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";
});
});
Create an array with the string you would like to cycle (strings)
Create an integer in which we will hold the current shown index (i)
Add click listener in which we will:
0element.innerHTML to the index of the arrayconst 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:
Fancy one-liner using the same logic as above
element.addEventListener("click", () => element.innerHTML = strings[(i === (strings.length - 1)) ? (i = 0) : ++i]);
Using the modulo operator (%) to set i
element.addEventListener("click", () => {
i = (i + 1) % strings.length
element.innerHTML = strings[i];
});