Reputation: 281
I have following to create for pagination:
<?php
for($i = 1; $i<=10; $i++){ ?>
<a class="pagenumber" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php } ?>
Now I want change the class pagenumber
to "pagenumberselected" if the href from pagenumber
includes ?p=5
from the current page (localhost/myproject/downsite?p=5
)
Upvotes: 0
Views: 361
Reputation: 21882
Since the class and link, are set on page load (via php), the class is defined at page load. Clicking the link is going to reload (or change) the page, if you want the class to change when the p = 5, you merely need a php conditional to target that page number and change the class (when the page loads).
<?php
for($i = 1; $i<=10; $i++){
if (i == 5 ) {
?>
<a class="pagenumber selected" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php } else { ?>
<a class="pagenumber" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a>
<php } } ?>
I would actually prefer the code below, but essentially they are both the same thing, it just depends on how you feel about echoing HTML as opposed to splitting it from PHP scripting.
<?php
for($i = 1; $i<=10; $i++){
if ($i == 5 ) {
//change link where p=5
echo '<a class="pagenumber selected" href="?p='.$i.'">'.$i.'</a>';
} else {
//all links where p!=5
echo '<a class="pagenumber" href="?p='.$i.'">'.$i.'</a>';
}
} ?>
You could do this with jQuery after the page loads, by checking the href of the link, then adding/removing classes. But then you're waiting for the page to load before implementing the change. By doing it in the php, the page loads as desired without waiting for javascript to load and function.
You could also just use the $_GET[]
variable to change the page link whenever the current page is equal to the link..
<?php
if (isset($_GET['p'])) {
$thispage = $_GET['p'];
} else {
$thispage = '';
}
for($i = 1; $i<=10; $i++){
if ($i == $thispage) {
//change link when link = current page
echo '<a class="pagenumber selected" href="?p='.$i.'">'.$i.'</a>';
} else {
//all links when link != current page
echo '<a class="pagenumber" href="?p='.$i.'">'.$i.'</a>';
}
} ?>
Upvotes: 1
Reputation: 272
You need to use $_GET
global array which handles parameters from your url. You can access to it, by parameter name like that: $_GET['p']
. It's also important to check if the parameter exists. You can achieve this by using isset
method. Solution:
<?php for($i = 1; $i <= 10; $i++): ?>
<?php if(isset($_GET['p']) && $_GET['p'] == $i): ?>
<a class="pagenumberselected" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php else: ?>
<a class="pagenumber" href="?p=<?php echo $i; ?>"><?php echo $i; ?></a>
<?php endif; ?>
<?php endfor; ?>
Upvotes: 0