I am cycling through elements within this array using the 'next' and 'previous' buttons. However I want to show the first element of the array, index [0] when the page is loaded, Rather than having to click 'next' to see the first one.
Would it be best to toggle the css class in some way? Or is there a simpler solution that can be done within the JS code?
<body>
<div id='entry1' class='entry'>
Entry1
</div>
<div class ='entry'>
Entry2
</div>
<div class ='entry'>
Entry3
</div>
<div class ='entry'>
Entry4
</div>
<p id="filler"></p>
<button id="back">PREVIOUS</button>
<button id="forward">NEXT</button>
</body>
<script>
var divs = document.querySelectorAll(".entry");
var i=-1;
var text = "";
document.getElementById("back").addEventListener("click", function
previous() {
if (i > 0) {
text = divs[--i].textContent;
}
document.getElementById("filler").innerHTML = text;
});
document.getElementById("forward").addEventListener("click", function
next(){
if (i < divs.length - 1) {
text = divs[++i].textContent;
}
document.getElementById("filler").innerHTML = text;
});
</script>
Here is my JS Fiddle:
You can simply initialize the p
with the text content of the first div. Also you now need to start from index 0
.
var divs = document.querySelectorAll(".entry");
var i=0;
// set the initial content to be the one from the first div
var text = divs[0].textContent;
var filler = document.getElementById("filler");
filler.innerHTML = text;
document.getElementById("back").addEventListener("click", function previous() {
if (i > 0) {
text = divs[--i].textContent;
}
filler.innerHTML = text;
});
document.getElementById("forward").addEventListener("click", function next(){
if (i < divs.length - 1) {
text = divs[++i].textContent;
}
filler.innerHTML = text;
});