JS: Pagination with Array

Vanilla JavaScript for paging through array.

by Daniel Pegues

HTML

<div id="output"></div>
<div>
    <a href="javascript:void(0);" id="prev_button" class="btn">PREV</a>
    <a href="javascript:void(0);" id="next_button" class="btn">NEXT</a>
</div>

CSS

#output {
  margin: 15px 0;
  padding: 15px;
  color: #393939;
  font-family: Arial, Helvetica, Sans-serif;
  font-size: 14px;
  line-height: 19px;
  background-color: rgba(255,0,0,0.10);
    
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  }

.btn {
  margin: 0 5px 0 0;
  padding: 8px 10px;
  display: inline-block;
  color: #393939;
  font-family: Arial, Helvetica, Sans-serif;
  font-size: 16px;
  font-weight: bold;
  text-decoration: none;
  background-color: #ffcb6d;
  
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  -webkit-transition: all 0.10s ease-in-out;
  -moz-transition: all 0.10s ease-in-out;
  -ms-transition: all 0.10s ease-in-out;
  -o-transition: all 0.10s ease-in-out;
  transition: all 0.10s ease-in-out;
  }
  .btn:hover {
    background-color: #bbbbff;
    }

JavaScript

// Array of Stored Records
var dataStore = ['My Data 1','My Data 2','My Data 3','My Data 4','My Data 5','My Data 6','My Data 7','My Data 8','My Data 9','My Data 10','My Data 11','My Data 12','My Data 13','My Data 14','My Data 15','My Data 16','My Data 17','My Data 18','My Data 19','My Data 20'];

var i = 0;

// Next Item in Array
function nextItem() {
    i = i + 1; // increase i by one
    
    i = i % dataStore.length; // if we've gone too high, start from `0` again
    
    return dataStore[i]; // give us back the item of where we are now
}

// Previous Item in Array
function prevItem() {
    if (i === 0) { // i would become 0
        i = dataStore.length; // so put it at the other end of the array
    }
    
    i = i - 1; // decrease by one
    
    return dataStore[i]; // give us back the item of where we are now
}

// Event Listener: Page Load
window.addEventListener('load', function () {

		// Load Initial to Selector, #output
    document.getElementById('output').textContent = dataStore[0]; // initial value
    
    // Event: Previous Button
    document.getElementById('prev_button').addEventListener('click',function (e) {
    		document.getElementById('output').textContent = prevItem();
    });
    
    // Event: Next Button
    document.getElementById('next_button').addEventListener('click',function (e) {
    		document.getElementById('output').textContent = nextItem();
    });
});