I have an array of strings and on click of the "NEXT" button it displays the next array item in a <p>
tag while on click of the "PREV" button it displays the previous one. When it reaches to the end (beginning) it continues from the first (last) item.
I have had some hard time to find a way to get the right item index when PREV is clicked and this is what i could have come up with.
I've used a modulo operator on decreasing array indices. I would like to know if there is a better way of doing this. By the way ES6 syntax is just what I like so I am not interested in any ES5 compatibility improvements.
var message = ["dog", "cat", "bear", "penguin", "tiger", "eagle", "John Doe"],
pel = document.getElementById("text"),
idx = 0,
getNext = e => pel.innerText = e.target.id == "right" ? message[idx = ++idx%message.length]
: message[idx = (message.length - (message.length - --idx)%message.length)%message.length];
document.getElementById("right").onclick = getNext;
document.getElementById("left").onclick = getNext;
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer ></script>
</head>
<body>
<p id="text">dog</p>
<button id="left" style = "width: 50px; background-color:gold" onclick="getNext">PREV</button>
<button id="right" style = "width: 50px; background-color:tomato" onclick="getNext">NEXT</button>
</body>
</html>