Search code examples
javascripthtmljquerycsscarousel

How to get next id for img


When I hover li with number 3 I get wrong number for next id in img. On first hover I get next id = 4, that's wrong. On second hover I get next id = 0 that's what I need. How to make correctly next id on hover like a carousel

let chosen_li = [];
let next_id;

$(".navigate li").on("mouseover", function () {
  let li = $(this);

  let index_li = li.index();

  chosen_li.unshift(index_li);
  if (chosen_li.length > 2) {
    chosen_li.pop();
  }
  if (chosen_li[0] !== chosen_li[1]) {
    $("#slider #img_" + chosen_li[0])
      .prependTo("#slider")
  }
  /////how to get next id?
  next_id =
    next_id > $(".navigate li").length - 1
      ? 0
      : parseInt($("#slider").children().attr("id").split("_")[1], 10) + 1;

  console.log(next_id);
  $("#slider #img_" + next_id).insertAfter($("#slider img:first"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="slider">
    <img id="img_0" src="1.jpg" style="margin-left:10px">
    <img id="img_1" src="2.jpg" style="margin-left:20px">
    <img id="img_2" src="3.jpg" style="margin-left:30px">
    <img id="img_3" src="4.jpg" style="margin-left:40px">
</div>

<ul class="navigate">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>


Solution

  • you need to get value of nextid from current element before comparison

    next_id = parseInt($("#slider").children().attr("id").split("_")[1], 10) + 1; 
    
    if (next_id > ($(".navigate li").length - 1) )
      next_id = 0;