How can I move tiles in circularly in a multi-row carousel?

Forums jQueryHow can I move tiles in circularly in a multi-row carousel?
Staff asked 2 years ago

Answers (1)

Add Answer
Prince Dhameliya Marked As Accepted
Staff answered 2 years ago

I used the index to absolute position formula (top, left). I then animated that using jQuery. That’s tacky, but if that’s a problem, it could be fixed. It appears nice.

const containerBox = document.querySelector('#container')
let divs = [...containerBox.querySelectorAll('div')]
var size = 100
var margin = 2

function get_top_left(pos) {
  if (pos < divs.length / 2) {
    return {
      left: pos * size + margin * (pos),
      top: 0
    }
  } else {
    return {
      left: (divs.length - pos - 1) * size + margin * (divs.length - pos - 1),
      top: size + margin
    }
  }
}

var offset = 0

function draw() {

  divs.forEach(function(div, index) {
    var len = divs.length
    index = ((index + offset) % len + len) % len
    var pos = get_top_left(index);
    //div.style.left = pos.left + "px"
    //div.style.top = pos.top + "px"
    $(div).animate({
      "left": pos.left + "px",
      "top": pos.top + "px"
    })
  })

}

next.onclick = _ => {
  offset += 1
  draw()
}
prev.onclick = _ => {
  offset -= 1
  draw()
}

draw();
#container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 500px;
  height: 260px;
  margin: 10px;
  position: relative;
}

#container>div {
  width: 100px;
  height: 66px;
  color: white;
  text-align: center;
  font-size: 24px;
  border: 1px solid white;
  padding-top: 34px;
  box-sizing: content-box;
  background: #2a80b9;
  position: absolute;
  top: 0;
  left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<div id="container">
  <div> 1 </div>
  <div> 2 </div>
  <div> 3 </div>
  <div> 4 </div>
  <div> 5 </div>
  <div> 6 </div>
</div>

 

Subscribe

Select Categories