Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

46
Views
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()">
7 months ago · Juan Pablo Isaza
1 answers
Answer question

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>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs