Home > database >  JQuery check if link is clicked not working
JQuery check if link is clicked not working

Time:12-07

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 >
   <li ><a  href="?page=login">1</a></li>
   <li ><a  href="#">2</a></li>
   <li ><a  href="#">3</a></li>
</ul>

CodePudding user response:

Here is your solution.

$(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());
        });
});

CodePudding user response:

$(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());
    });

});

  • Related