Home > OS >  Can this div elements slider work with my script?
Can this div elements slider work with my script?

Time:10-24

I built this piece with the intention of making it slide towards the left, infinitely, using vanilla JavaScript.

In JavaScript, I used the setInterval function to decrement the sliding motion by 210 pixels for every 1000 milliseconds.

There are nine div elements in the inner slider. Also, in CSS, I used transitioning to give it the sliding effect.

setInterval(function() {
  document.getElementById('inner').scrollLeft -= 210
}, 1000)
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Yu Gothic UI';
  background-color: #e0e0e0;
}

main {
  height: 100vh;
  width: 100%;
  display: grid;
  place-items: center;
}

div.slider_container {
  height: 160px;
  width: 80%;
  overflow: hidden;
  border: 1px solid #000;
  position: relative;
}

div.inner {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  height: 100%;
  display: grid;
  grid-template: 1fr / repeat(9, 160px);
  grid-column-gap: 10px;
  transition-property: all;
  transition-duration: 1000ms;
  transition-timing-function: linear;
}

div.inner div.item {
  display: grid;
  place-items: center;
  border: 1px solid #000;
}

div.inner div.item span {
  text-transform: capitalize;
  font-size: 30px;
}

div.inner div.item:nth-child(1) {
  color: yellow;
}

div.inner div.item:nth-child(2) {
  color: sienna;
}

div.inner div.item:nth-child(3) {
  color: dodgerblue;
}

div.inner div.item:nth-child(4) {
  color: magenta;
}

div.inner div.item:nth-child(5) {
  color: red;
}

div.inner div.item:nth-child(6) {
  color: rebeccapurple;
}

div.inner div.item:nth-child(7) {
  color: dimgray;
}

div.inner div.item:nth-child(8) {
  color: salmon;
}

div.inner div.item:nth-child(9) {
  color: lime;
}
<main>
  <div >
    <div  id="inner">
      <div >
        <span>item 1</span>
      </div>
      <div >
        <span>item 2</span>
      </div>
      <div >
        <span>item 3</span>
      </div>
      <div >
        <span>item 4</span>
      </div>
      <div >
        <span>item 5</span>
      </div>
      <div >
        <span>item 6</span>
      </div>
      <div >
        <span>item 7</span>
      </div>
      <div >
        <span>item 8</span>
      </div>
      <div >
        <span>item 9</span>
      </div>
    </div>
  </div>
</main>

I know my JavaScript may look funny and unprofessional :D (the pros out there can tell), which is the reason I had to come here for help. Thank you.

CodePudding user response:

slider_container is the parent element that has overflow and is scrollable. Therefore select the slider_container in your script instead of inner.

setInterval(function() {
  document.querySelector('.slider_container').scrollLeft  = 210
}, 1000)

See example here on JSFiddle

  • Related