skip to Main Content

I have a bootstrap pagination. I want if a page was clicked just get a red background and stay. to show which page is currently active.
the problem is when the page reloads after clicking, the background doesn’t remain and wanished.
how to fix this?

ps. this code works fine for other elements but links and buttons, means the problem is just reloading and I need reloading. I put an alert just for test in JS.

ps2. I don’t want all links get background color after visiting, its pagination and only active page must get.

$('.page-link').on('click',function (){
        alert('ok');
        $(this).addClass('active-page');
    })
.active-page{
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>


<ul class="pagination">
   <li class="page-item"><a class="page-link" href="?page=login">1</a></li>
   <li class="page-item"><a class="page-link" href="#">2</a></li>
   <li class="page-item"><a class="page-link" href="#">3</a></li>
</ul>

2

Answers


  1. <ul class="pagination">
          <li class="page-item"><a class="page-link" href="#">Prev</a></li>
          <li class="page-item"><a class="page-link" href="#">1</a></li>
          <li class="page-item"><a class="page-link" href="#">2</a></li>
          <li class="page-item"><a class="page-link" href="#">3</a></li>
          <li class="page-item"><a class="page-link" href="#">Next</a></li>
    </ul>
    

    Here is your solution.

    $(document).ready(() => {
        let activePage = localStorage.getItem("activePage");
    
        if (activePage === "Prev") {
          $(".page-link").eq(0).addClass("active-page");
          localStorage.removeItem("activePage");
        } else if (activePage === "Next") {
          $(".page-link")
            .eq($(".page-link").length - 1)
            .addClass("active-page");
          localStorage.removeItem("activePage");
        } else if (activePage === null) {
        } else {
          $(".page-link").eq(activePage).addClass("active-page");
          localStorage.removeItem("activePage");
        }
    
        $(".page-link").on("click", function () {
            $(this).addClass("active-page");
            localStorage.setItem("activePage", $(this).text());
        });
    });
    
    Login or Signup to reply.
  2. $(document).ready(() => {
    let activePage = localStorage.getItem("activePage");

        if (activePage) {
          $(".page-link")
            .eq(activePage - 1)
            .addClass("active-page");
          localStorage.removeItem("activePage");
        }
    
        $(".page-link").on("click", function () {
          $(this).addClass("active-page");
          localStorage.setItem("activePage", $(this).text());
        });
    

    });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search