Continuous Slide - without loop

by Julien Etienne

HTML

<section>
  <nav>
    <div>One</div>
    <div>Two</div>
    <div>Three</div>
    <div>Four</div>
    <div>Five</div>
  </nav>
</section>

<button id="prev">Prev</button><button id="next">Next</button>


<div id="direct">
  <button id="0">1</button>
  <button id="1">2</button>
  <button id="2">3</button> 
  <button id="3">4</button>
  <button id="4">5</button>
</div>

CSS

section {
  width: 400px;
  height: 200px;
  border: 1px solid lime;
  position: relative;
  /* overflow: hidden; */
}

nav {
  display: grid;
  grid-auto-flow: column;
  height: 200px;
  transform-origin: 50% 50%;
  transition: all 400ms ease;
  left:0;
  position: absolute;
}

div {
  width: 400px;
  height: 200px;
  font-size: 6rem;
  display: grid;
  justify-content: center;
  align-content: center;

  &:nth-child(1) {
    background: lightblue;
  }

  &:nth-child(2) {
    background: lightgreen;
  }

  &:nth-child(3) {
    background: lightgray;
  }

  &:nth-child(4) {
    background: lightyellow;
  }

  &:nth-child(5) {
    background: lightpink;
  }
}

JavaScript

const list = document.querySelector('nav')
const items = Array.from(list.children)
const prev = document.querySelector('#prev')
const next = document.querySelector('#next')

const width = 400
const height = 200

const {
  abs
} = Math

// Get last item and place it next to first
// list.insertAdjacentElement('afterbegin', list.lastElementChild)

// Move one back
// let transform = -width
 let transform = 0
list.style.transform = `translate3d(${transform}px, 0,0)`

let index = 0
let lastIndex = 0
document.addEventListener('mousedown', ({
  target
}) => {
  let dir
  if (target === next) {
    if (index >= items.length - 1) {
      index = 0
    } else {
      index++
    }
    dir = true
  }

  if (target === prev) {
    if (index === 0) {
      index = items.length - 1
    } else {
      index--
    }
    dir = false
  }

if (target.closest('#direct')) {
    index = target.id
}


  let range
  const isRight = index > lastIndex

  if (isRight) {
    range = index - lastIndex
  } else {
    range =  index - lastIndex
  }


  console.log(index, lastIndex, range, isRight)

	console.log('T', transform)
  if (dir) {
    transform -= range * width
  } else {
    transform -= range * width
  }
 
  list.style.transform = `translate3d(${transform}px, 0,0)`


  lastIndex = index
})