Select each element in a selection loop. If you go forward as soon as you finish the list of elements you will start selecting from the beginning and the same if you go in opposite direction.
JavaScript HTML CSSdocument.querySelector('#next').addEventListener('click', () => {
const $selected = document.querySelector('.selected');
const $next_element = $selected.nextElementSibling;
if (!$next_element)
$next_element = $selected.parentElement.firstElementChild;
$selected.classList.remove('selected');
$next_element.classList.add('selected');
});
document.querySelector('#previous').addEventListener('click', () => {
const $selected = document.querySelector('.selected');
const $previous_element = $selected.previousElementSibling;
if (!$previous_element)
$previous_element = $selected.parentElement.lastElementChild;
$selected.classList.remove('selected');
$previous_element.classList.add('selected');
});
<button id="previous">Previous</button>
<button id="next">Next</button>
<ul>
<li></li>
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
</ul>
button {
font-size: 2vw;
border-radius: 2vw;
border: 0.5vw solid #ccc;
padding: 1vw 2.5vw;
cursor: pointer;
text-transform: uppercase;
color: #50514F;
}
button:focus {
outline: none;
}
li {
display: inline-flex;
list-style-type: none;
width: 10vw;
height: 10vw;
border-radius: 50%;
background-color: #50514F;
}
li.selected {
border: 1vw solid #9BC53D;
;
}
Don’t forget to use nextElementSibling and previousElementSibling (DOM Elements) instead of nextSibling and previousSibling (DOM Objects). A DOM Object can be anything: comments, insolated text, line breaks, etc. In our example nextSibling would have worked if we had set all our HTML Elements together without anything between then:
<ul><li></li><li></li></ul>