Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

77
Vistas
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;

}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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;

}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda