Caleb Morgan
Caleb Morgan

Reputation: 23

Unable to change the active pagination button as it refreshes using php

I am trying to change the active pagination button when I click on it but it refreshes and remains the same as I get data after refresh. Here is the code:

<?php
    for ($page=1;$page<=$number_of_pages;$page++) {
    ?>
        <li class="page-item"><a class="page-link" href="view_videos.php?page=<?php echo $page;?>"><?php echo $page; ?></a></li>               
    <?php  
    }
?>

I will be getting urls as:

domain.com/hello.php?page=1
domain.com/hello.php?page=2

When I click on the second button the url changes to domain.com/hello.php?page=2 then I want change the background of second button color as active but due to page refresh its not becoming active.

Here is a screenshot of my navigation bar

enter image description here

Upvotes: 2

Views: 850

Answers (2)

You have to get the page number from the URL after the page loads, and check it against each page indicator to see if it is the active one. Then you can add a class active, and style that in your CSS.

So you can try this:

<?php
    for ($page = 1; $page <= $number_of_pages; $page++) { 
        if ($page === $_GET["page"]) {
            $active = " active";
        } else {
            $active = "";
        }
    ?>
        <li class="page-item">
            <a class="page-link <?= $active ?>" href="view_videos.php?page=<?= $page ?>"><?= $page ?></a>
        </li>
    <?php
    }
?>

Note: <?= $foo ?> is the same as <?php echo $foo ?> manual

Upvotes: 0

Jeroen Bellemans
Jeroen Bellemans

Reputation: 2035

Very simple:

Get the page_id like this:

$page_id = isset($_GET['page']) ? $_GET['page'] : false;

Now you have the number of the current page you are on

Then inside the loop, you could do another check like this:

<li class="page-item<?php echo ($page_id == $page) ? ' my-background' : '' ?>"><a class="page-link" href="view_videos.php?page=<?php echo $page;?>"><?php echo $page; ?></a></li>

Then you could do this in your .css-file:

.my-background {
    background-color: #FF0000; /* Maybe add "!important" if necessary */
}

Upvotes: 4

Related Questions