-1

Trying to make it so this counter with buttons increases or decreases based on clicks, however on the first click the counter doesn't increase. If I do + 1 it will but then will stop. ++works but only after first click. Trying to learn easy way to resolve my code that isn't a drastic change.

https://jsfiddle.net/sy0ohtrc/

var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.innerHTML = pageCount; 

//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);


function nextPage() {
    var elPageIncrease = document.getElementById("currentPage");
    elPageIncrease.innerHTML = pageCount++;
}


var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);

function prevPage() {
    var elPageDecrease = document.getElementById("currentPage");
    elPageDecrease.innerHTML = pageCount--;
}

1 Answers1

1

You should use --/++ before the counter because when you use the increment/decrement operator after, the value will be returned before the it increased/decreased.

AND there is no need for declaring 3 time the same element.

Finally change the innerHTML to textContent (and if you want to know why read this thread).

Your code should look something like that:

var pageCount = 1;
var elPage = document.getElementById("currentPage");
elPage.textContent = pageCount;

//Get next button and add connect function on click
var elNext = document.getElementById("nextButton");
elNext.addEventListener("click", nextPage);


function nextPage() {
//    var elPageIncrease = document.getElementById("currentPage"); you have elPage already pointing this element
    elPage.textContent = ++pageCount;
}


var elPrev = document.getElementById("prevButton");
elPrev.addEventListener("click", prevPage);

function prevPage() {
//    var elPageDecrease = document.getElementById("currentPage");  you have elPage already pointing this element
    elPage.textContent = --pageCount;
}
<div class="pager">
  <button id="prevButton">prev</button>
  <p class="pageNumber" id="currentPage"></p>
  <button id="nextButton">next</button>
</div>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34