Home > Blockchain >  Javascript show next prev content appenchild
Javascript show next prev content appenchild

Time:05-24

enter image description hereI have multiple divs with same class and I need put only one of class to some id, It show me not right order. And also if I will have some dropdown menu and I will click of some div with class, need to show this class in id. Here is my code, could you please help me. Thanks

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs((slideIndex  = n));
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = x.length;
  }
  for (i = 0; i < x.length; i  ) {
    x[i].style.display = "none";
    document.getElementById("back").appendChild(x[i]);
  }
  x[slideIndex - 1].style.display = "block";
  document.getElementById("get").appendChild(x[slideIndex - 1]);
}
#get {
  height: 300px;
  width: 500px;
  border: 1px solid red;
  left: 100px;
  position: absolute;
}

#get .mySlides {
  display: block!important
}
<button onclick="plusDivs(-1)"><</button>
<button onclick="plusDivs(1)">></button>
<div id="back">
  <div id="one" >
    <span >111</span>
  </div>
  <div id="two" >
    <span >222</span>
  </div>
  <div id="three" >
    <span >333</span>
  </div>
</div>
<div id="get"></div>

CodePudding user response:

In javascript first's elements index is zero, not 1.

const
  dGet   = document.getElementById('get')
, dBack  = document.getElementById('back')
, slides = document.querySelectorAll('.mySlides')
, current = 
  { slide : null
  , index : 0
  , len   : slides.length
  }; 

 
plusDivs(0);

function plusDivs(n)
  {
    // more easy with a modulo...
  current.index = (current.index  n  current.len) % current.len;
  
  if (current.slide) dBack.appendChild( current.slide )
  
  current.slide = dGet.appendChild( slides[current.index] )
  }
#get {
  height   : 300px;
  width    : 500px;
  border   : 1px solid red;
  left     : 100px;
  position : absolute;
  }
#back {
  display : none;
  }
<button onclick="plusDivs(-1)"><</button>
<button onclick="plusDivs(1)">></button>
<div id="back">
  <div id="one" >
    <span >111</span>
  </div>
  <div id="two" >
    <span >222</span>
  </div>
  <div id="three" >
    <span >333</span>
  </div>
</div>
<div id="get"></div>

  • Related