I have pagination and I'm trying to change the currentPage variable and execute some more code based on which page the user clicked, however, I'm having some trouble accessing the data-id attribute in the .click
function that executes on click. From what I've seen, I'm supposed to get it using $(this).data("id")
, however, this returns undefined
for me.
$(document).ready(function () {
let currentPage = 1;
let totalPages = 100;
const renderPagination = () => {
totalPages = 100;
const paginationContainer = $(".pagination-container");
paginationContainer.empty();
let numShown = 5;
numShown = Math.min(numShown, totalPages);
let first = currentPage - Math.floor(numShown / 2);
first = Math.max(first, 1);
first = Math.min(first, totalPages - numShown + 1);
const limitedPagination = [...Array(numShown)].map((k,i) => i + first);
limitedPagination.forEach((page, i) => {
paginationContainer.append(`<p class="page" data-id="${page}">${page}</p>`)
});
$(".page").click(() => {
console.log($(this).data("id"));
});
}
renderPagination();
});
.pagination-container {
display: flex;
justify-content: center;
align-items: center;
}
.page {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
height: 50px;
padding: 10px;
border: 1px
solid #ddd;
margin-right: 10px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.page:last-child {
margin-right: 0px;
}
.page:hover {
border: 1px solid #aaa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pagination-container"></div>