'change text using arrays and button next

I am trying to use the elements on the array contenidoHistoria and actually created this function that responds to an event listener. But is only showing me the first element of the array and not the other elements as i press the button

var botonSiguiente = document.createElement('button')
botonSiguiente.setAttribute('id', 'siguiente')
botonSiguiente.innerText = 'Siguiente'
optionButtons = document.getElementById('option-buttons').appendChild(botonSiguiente)
document.getElementById('siguiente').addEventListener('click', siguiente, true)

//creating a 'sguiente' button event
var siguiente = function() {
var no_of_clicks = 0
//array that contains the infomration to pass everytime the button is clicked
var contenidoHistoria = ['texto 1', 'texto 2', 'texto 3', 'texto 4', 'texto 5']
var base = document.getElementById('base');
    base.innerHTML = `<p> ${contenidoHistoria[no_of_clicks]}</p>`
no_of_clicks == (contenidoHistoria.length - 1) ? no_of_clicks = 0 : no_of_clicks = no_of_clicks + 1;

}


Solution 1:[1]

The problem is that you define no_of_clicks every time the function siguiente is run, so it is reset to 0 on every click. If you take no_of_clicks out of the function, it will work as you intend. Also, it's a better practice to use let and const rather than using var as it prevents hoisting. I also took out contenidoHistoria outside of the function as well since it is also not something you need to create every time the function is run. :


let no_of_clicks = 0
//array that contains the infomration to pass everytime the button is clicked
const contenidoHistoria = ['texto 1', 'texto 2', 'texto 3', 'texto 4', 'texto 5']

const siguiente = function() {
  const base = document.getElementById('base');
  base.innerHTML = `<p> ${contenidoHistoria[no_of_clicks]}</p>`
  no_of_clicks == (contenidoHistoria.length - 1) ? no_of_clicks = 0 : no_of_clicks = no_of_clicks + 1;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1