• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

148
Vistas
How to increment a class number to switch divs?

I would like to switch my divs (I'm creating a div carousel style) with their class name. So I would like to increment and decrement (to go 'next' and 'previous') the "box'1'" number to switch between them anytime I click on the buttons, which contain the js functions

<div class="box1"> ...
</div>
<div class="box2"> ...
</div>
<div class="box3"> ...
</div>
<div class="box4"> ...
</div>

I found some fixes on this site but still I wasn't able to use them for my code. So I tried this :

function increase() {
  var a = 1;
  var boxes = document.getElementById("box1");
  boxes.value = a;
  a++;
}

function decrease() {
  var a = 1;
  var boxes = document.getElementById("box1");
  boxes.value = a;
  a--;
}

And

<input class="buttongray" value="next" onclick="increase()">
<input class="buttonblue" value="back" onclick="decrease()">
almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

let box = document.querySelectorAll('.box');
let ctr = 0;
// onload fill box 1
box[ctr].style.display = "block";
box[ctr].innerHTML = "Box On " + (ctr+1);

function ctrSwitch(n) {
  // int counter
  ctr += n;

  // counter check max and min
  ctr = (ctr>=box.length)? 0 : (ctr < 0) ? box.length-1: ctr;

  // loop and match active box by counter
  box.forEach((el, i) => {
    /* @param el = box[i] */
    // option 1 (use ternary);
    // box[i].innerHTML = (ctr == i)? `Box On ${ctr+1}` : "...";

    // option 2 (use if else);
    if ( ctr == i ) {
       el.style.display = "block";
       el.innerHTML = `Box On ${ctr+1}`;
    }
    else {
       el.style.display = "none";
       el.innerHTML = `...`;
    }
  });
}
.box {
  width: 50px;
  height: 50px;
  display: none;
  color: #fff;
}

.box1 {
  background: red;
}
.box2 {
  background: green;
}
.box3 {
  background: blue;
}
.box4 {
  background: purple;
}
<div class="box box1"> ...
</div>
<div class="box box2"> ...
</div>
<div class="box box3"> ...
</div>
<div class="box box4"> ...
</div>
<button onclick="ctrSwitch(-1)">Prev</button>
<button onclick="ctrSwitch(1)">Next</button>

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda