I am creating a function in JS to create a pagination nav bar. It is suppose to get the total amount of pages and loop through that many times in order to create the proper divs and finally add an onclick function to each created div.
I managed to create the divs with no problem using the for 'i' value to add the ID and innerHTML for each, but the onclick function should also receive the same 'i' value but it won't. I changed the proper function for a simple console.log(i) because the issue is that instead of getting the proper 'i' value the response is 3 in every button. This is the code:
function create_pagination(totalPages, hasNext, hasPrevious) {
if (document.querySelector('.page-number') != null) {
document.querySelectorAll('.page-number').forEach((e) => e.remove());
}
for (i = 1; i < totalPages + 1; i++) {
let previousDiv = document.querySelector('#hasPrevious');
let nextDiv = document.querySelector('#hasNext');
let parentDiv = document.querySelector('#pagination');
if (hasPrevious) {
previousDiv.style.display = 'block';
}
if (hasNext && hasPrevious === false) {
nextDiv.style.display = 'block';
}
pageItemDiv = document.createElement('li');
pageItemDiv.classList.add('page-item');
pageItemDiv.classList.add('page-link');
pageItemDiv.classList.add('page-number');
pageItemNumber = document.createElement('a');
pageItemNumber.id = `${i}`;
pageItemNumber.innerHTML = `${i}`;
pageItemNumber.onclick = () => console.log(i);
pageItemDiv.appendChild(pageItemNumber);
parentDiv.insertBefore(pageItemDiv, nextDiv);
}
}
Thanks in advance for your support!