I have a slider which will go through each function in an array functions, also I have another array with data, when I call for a function to display data in the console it shows my array[], but when I want to display the data from the array[] in div it shows undefined. What should I do?
const textContent = document.getElementById("textContent");// a div
const next = document.getElementById("next");// a button
const prev = document.getElementById("prev");// a button
const array = [
"They both die at the end",
"What if it's us",
"Tuesday with Morrie",
"Second life of Ove",
"Flowers for Algernon",
"The Minds of Billy Milligan",
"The Fifth Sally",
"The Touch",
"Adele",
"The Girl Before"
];
function first(){
console.log("1");
};
function second(){
for(item in array){
textContent.innerHTML = `${array[item]}<br>`;
}
};
function third(){
console.log("3");
};
function four(){
console.log("4");
};
function five(){
console.log("5");
};
const functions = [
first,
second,
third,
four,
five
];
number = 0;
function skip() {
if(number > functions.length - 1){
number = 0;
}
if(number < 0){
number = functions.length - 1;
}
f = functions[number];
textContent.innerHTML = f();
}
next.addEventListener("click", () => {
number = 1;
skip();
})
prev.addEventListener("click", () => {
number -= 1;
skip();
})
CodePudding user response:
In your skip function, you are setting textContent.innerHTML
to be the result of the current function. And your second
function is not returning anything.
You can either return results from all the functions like this
function second(){
let innerHTML = "";
for(const item in array){
innerHTML = `${array[item]}<br />`;
}
return innerHTML;
};
Or in your skip function, call the current function and avoid setting innerHTML
to its return value.
f = functions[number];
f();
You can see a working demo here https://codepen.io/abito12/pen/RwMRqro