How to move slider preview slow

Advertisements

I need the slider preview to move by image but now it moves immediately to the end

I tried creating the preview slider with two buttons: left and right but when I pressed right it moved to the end, while I need it to move by image
Here is the link:
https://codepen.io/alexvambato/pen/yLGBxKK

<div class="img-container1" style="float:left; margin:10px;max-width: 530px">
<!-- Create slider. -->
<style>
/* See the styles on codepen.io */
</style>
<div id="thumbelina" style="padding:5px;overflow: hidden;">
<button class="btnToLeft" onclick="toMovel()"><</button>
    <ul id="thumbelina0" style="padding:0px; width:max-content; text-align:center;display: flex;margin-bottom: 0px;margin-left: 0px;">
    <li style="padding:5px;width: auto;height: 100px;display: block;"><img src="{{preview_image}}" style="margin-top: -5px;margin-left: -5px;" /></li>
      <li style="padding:5px;width: auto;height: 100px;display: block;"><img src="{{preview_image}}"  style="margin-top: -5px;margin-left: -5px;" /></li>
      <li style="padding:5px;width: auto;height: 100px;display: block;"><img src="{{preview_image}}"  style="margin-top: -5px;margin-left: -5px;" /></li>
      <li style="padding:5px;width: auto;height: 100px;display: block;"><img  style="margin-top: -5px;margin-left: -5px;" /></li>
      <li style="padding:5px;width: auto;height: 100px;display: block;"><img src="{{preview_image}}"  style="margin-top: -5px;margin-left: -5px;" /></li>
      <li style="padding:5px;width: auto;height: 100px;display: block;"><img src="{{preview_image}}" style="margin-top: -5px;margin-left: -5px;" /></li>
    </ul>
<button class="btnToRight" onclick="toMove()">></button>
</div>
</div>
<script>
function toMove() { 
var move = document.querySelector('#thumbelina0');
move.setAttribute('style', 'padding:0px; width:max-content; text-align:center;display: flex;margin-bottom: 0px;margin-left: -300px;')
}
function toMovel() { 
var move = document.querySelector('#thumbelina0');
move.setAttribute('style', 'padding:0px; width:max-content; text-align:center;display: flex;margin-bottom: 0px;margin-left: 0px;')
}
</script>

>Solution :

You need to get the width of the current image and increase/decrease the container’s margin based on that value, not a fixed -300px or 0px.

Didn’t test it but this could work:

let currentIndex = 0;

function toMove() { 
  const slider = document.querySelector('#thumbelina0');
  const element = document.querySelectorAll('li')[currentIndex];
  
  // there seems to be a hard-coded 10px in your style
  slider.style.marginLeft = parseInt(slider.style.marginLeft) - element.offsetWidth - 10 + 'px';
  
  currentIndex++;
}

For moving elements to left, it’s a reverse action, so you just need to start adding the element width instead of subtracting it.

This is a quick-and-dirty solution but my suggestion is to use scroll offset instead of working with CSS like margin-left.

Leave a ReplyCancel reply