Reputation: 163
I have a menu with 5 different hrefs.
Each href refers to the same page but a different ID:
<a href="Planning.php?id=1" id="MenuButton1" class="MenuButton">Line 1</a>
<a href="Planning.php?id=2" id="MenuButton2" class="MenuButton">Line 2</a>
<a href="Planning.php?id=3" id="MenuButton3" class="MenuButton">Line 3</a>
<a href="Planning.php?id=4" id="MenuButton4" class="MenuButton">Line 4</a>
<a href="Planning.php?id=5" id="MenuButton5" class="MenuButton">Line 5</a>
Now I want something in my code that changes the class(for css purposes) of a href
when I got a certain ID. Something like a selected href.
Is it possible to change my class via php or javascript?
For instance:
if($_GET['id'] == 1)
{
MenuButton1.class= "SelectedLink";
}
Upvotes: 0
Views: 71
Reputation: 6251
If $_GET['id'] is equal to $i,use class SelectedLink instead of MenuButton.
<?
for ($i=0; $i < 5; $i++) {
?>
<a href="Planning.php?id=<?=$i+1?>" id="MenuButton<?=$i+1?>" class="<?=$i!=($_GET['id']-1)?'MenuButton':'SelectedLink'?>">Line <?=$i+1?></a>
<?
}
?>
Upvotes: 0
Reputation: 9123
Instead of just assigning a class you could do the following:
<a href="Planning.php?id=1" id="MenuButton1" class="MenuButton<?= (isset($_GET['id']) && $_GET['id'] == 1) ? ' SelectedLink' : ''; ?>">Menu Item 1</a>
That way, class SelectedLink
will only be assigned if $_GET['id']
is `.
You could also build your complete menu using PHP like this:
// Create an array containing your menu items
$menuItems = array(
'1' => 'Line 1',
'2' => 'Line 1',
'3' => 'Line 1',
'4' => 'Line 1',
'5' => 'Line 1',
);
<!-- Loop through the array and write your menu items -->
<?php foreach ($menuItems as $item => $name): ?>
<a href="Planning.php?id=<?= $item; ?>" id="MenuButton<?= $item; ?>" class="MenuButton<?= (isset($_GET['id']) && $_GET['id'] == $item) ? ' SelectedButton' : ''; ?>">Menu Item <?= $name; ?></a>
<?php endforeach; ?>
The above foreach will write your menu items. As said before, in the class I have used an shorthand if statement. This will check if the current looping menu item matches your $_GET
parameter. If so, it will write an extra class.
Upvotes: 1
Reputation: 2659
You can change the css class description based on the element tagname, and attributes using or not regular expressions depending what you want to do. For example:
.MenuButton { color: black; }
.MenuButton[id=MenuButton2] { color: red; }
.MenuButton[href$='1'] { color: green; } /* all ending with 1 - ie. 1 11 111 */
.MenuButton[href$='=1'] { color: blue; } { color: blue; } /* just =1 */
Upvotes: 0