Three evenings struggled with this problem, but could not solve it, more and more nuances came to light.

Actually the essence of the problem:

There is an array (dynamic) with images, a block for them, two buttons (forward, backward) as well as a block with all elements from the array, by clicking on one of them the handler must determine which path to the new array element from the old will be shorter (this My point is that to simplify the cycle, you can in your own way (for example, if there are only 11 elements, the current index is 1, the new one is 10. then the path to 10 will be shorter in the opposite direction (0, 11, 10) and not 2, 3 4 ... 10).

From 1 to 5 (not more) elements (4 after him and himself) are put in the block, if the length of the array allows. That is, if the current index is 10, then there should be images 10, 11, 0, 1, 2 in the block.

let array = ["image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg","image.jpg"], handler = (index) => { let current = this.current; this.current = index; /* обработчик */ } this.current = 0; back.addEventListener('click', ()=>handler( this.current - 1 in array ? this.current - 1 : array.length - 1 )); forward.addEventListener('click', ()=>handler( this.current + 1 in array ? this.current + 1 : 0 )); for (let key in array) { let v = array[key], li = document.createElement("LI"); li.addEventListener('click', ()=>handler(key)); all.appendChild(li); } 
 ul { list-style: none; margin: 0px; padding: 0px; min-height: 48px; width: 100%; } li { margin: inherit; padding: inherit; display: inline-block; border: 1px solid black; min-width: 48px; min-height: 48px; } #block { background-color: rgba(0, 0, 0, .1) } 
 <ul id="block"></ul> <button id="back">Назад</button> <button id="forward">Вперед</button> <ul id="all"></ul> 

  • 1. there is no question 2. what you need is called 'carousel' 3. similar questions 222 pieces 4. “unnecessary” elements are easier to hide hidden=true - qwabra
  • @qwabra 1. The question is opened therefore there are no question marks. 2. No. 4. "The block is placed from 1 to 5 (not more) elements" - linkterious
  • I am glad that you have your point of view on the first point, I hope this will help you in solving the problem - qwabra
  • just track the position of the scroll, as soon as the end of the data is close, request an addition - sair

1 answer 1

the easiest way to use the operation of integer modulo division (what is the operator for this in JS?)

 for (i = startIdx; i < startIdx + count; i++) use A[(startIdx + i) %% A.Length ] 

when decreasing, it also works, only use something like this:

  A[(startIdx - 1 + A.Length) %% A.Length ]