0

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>
Onyx
  • 5,186
  • 8
  • 39
  • 86
  • I do not see a `data-id` attribute on the element initially. When is this added? – Twisty Nov 02 '21 at 21:44
  • Don't use an arrow function as an event listener, it doesn't get the correct `this`. – Barmar Nov 02 '21 at 21:45
  • @Twisty When I append the pagination pages with JavaScript – Onyx Nov 02 '21 at 21:46
  • @Bobimaru you might want to try `$(this).attr("data-id")` and see if you get the correct result. If you need more help, please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Nov 02 '21 at 21:58

0 Answers0