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>
hidden=true- qwabra