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

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

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