0

I have written code with a click function. If the user clicks "next", set class "onscreen" to the next element.
What I want is the element that has class "onscreen" to scroll to top with animation duration of 1s.

This is my code:

HTML

<div class="slides">
  <div class="slide onscreen" id="one">one</div>
  <div class="slide" id="two">two</div>
  <div class="slide" id="third">third</div>
  <div class="slide" id="fourth">fourth</div>
</div>

<div class="buttons">
  <button class="next" onclick="slide(this.className)">
  Next slide
  </button>

  <button class="prev" onclick="slide(this.className)">
  Previous slide
  </button>
</div>

CSS

.buttons{
    width:170px;
    position:fixed;
    top:10px;
    left:50%;
    margin-left:-85px;
}

.onscreen {
  background-color: green;
}

Javascript

window.onload = function() {
  var slide = document.getElementsByClassName("slide");
  for (var i = 0; i < slide.length; i++) {
    var heightslide = slide[i].offsetHeight;
  }
  console.log(heightslide);
}
var active = document.getElementsByClassName("onscreen");

function slide(prevnext) {
  if (prevnext === "next") {
    if (active[0].nextElementSibling) {
      active[0].nextElementSibling.className = "slide onscreen";
      active[0].className = "slide";

    }

  } else {
    if (active[0].previousElementSibling) {
      active[0].previousElementSibling.className = " slide onscreen ";
      active[active.length - 1].className = "slide";
    }
  }
}

Hope somebody can help me with this.

Thanks a lot

George Kagan
  • 5,913
  • 8
  • 46
  • 50
Bryan
  • 1
  • 3
  • `element.scrollIntoView({behavior: "smooth"});` [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) – Dimava Sep 29 '16 at 20:00
  • more details http://stackoverflow.com/questions/4801655/how-to-go-to-a-specific-element-on-page – Tom Woodward Sep 29 '16 at 20:02
  • Thanks for the reactions! I saw a lot of examples on the internet, but how do I implement a scroll top function in my code? Javascript must scroll the right div element, which has class "on screen" – Bryan Sep 29 '16 at 20:59
  • Google "scroll to top jquery" where you'll find many tutorials on how to accomplish what you've asked – evolutionxbox Sep 29 '16 at 23:48
  • Possible duplicate of [Scroll to the top of the page using JavaScript/jQuery?](https://stackoverflow.com/questions/1144805/scroll-to-the-top-of-the-page-using-javascript-jquery) – leonheess Mar 12 '19 at 10:12

0 Answers0