php - How to change a link to active state using an onclick function in javascript
I have a common side navigation bar where I have linked several pages to it. I have included it to all the pages using the below php include statement.
<?php include '../php/playersidenav.php';?>
The sidenavigation is as follows.
<div class="column sidenav">
<div class="row">
<img src="../images/avatar.png" alt="Avatar">
<h1 style="color:white;float:right;padding-top:7%">Hello John!</h1>
</div>
<a class="normal" href="news.php" onclick="makeActive(event)">NEWS</a>
<a class="normal" href="schedule.php" onclick="makeActive(event)">SCHEDULE</a>
<a class="normal" href="partners.php" onclick="makeActive(event)">PARTNERS</a>
<a class="normal" href="coaches.php" onclick="makeActive(event)">COACHES</a>
<a class="normal" href="tournaments.php" onclick="makeActive(event)">TOURNAMENTS</a>
<a class="normal" href="events.php" onclick="makeActive(event)">EVENTS</a>
<a class="normal" href="shops.php" onclick="makeActive(event)">SHOPS</a>
</div>
Answer
Solution:
One way that you could do it would be to make use of the browser's localStorage
- If you modify the above playersidenav.php
slightly by removing the inline event handler like this and then including some Javascript within this file so that it looks like this:
<div class="column sidenav">
<div class="row">
<img src="../images/avatar.png" alt="Avatar">
<h1 style="color:white;float:right;padding-top:7%">Hello John!</h1>
</div>
<a class="normal" href="news.php">NEWS</a>
<a class="normal" href="schedule.php">SCHEDULE</a>
<a class="normal" href="partners.php">PARTNERS</a>
<a class="normal" href="coaches.php">COACHES</a>
<a class="normal" href="tournaments.php">TOURNAMENTS</a>
<a class="normal" href="events.php">EVENTS</a>
<a class="normal" href="shops.php">SHOPS</a>
</div>
<script>
//The name of the store in localStorage
const store='LINK_ACTIVATED_MEMORY';
// the class to add to indicate active state
const cn='active';
// nodelist of all sidenav links
const links=document.querySelectorAll('.sidenav > a.normal');
// ensure any "active" links have class removed and then
// save new hyperlink to localStorage
const makeActive=(e)=>{
e.preventDefault();
links.forEach(a=>a.classList.remove(cn));
localStorage.setItem( store, e.target.href );
location.href=e.target.href;
};
// on page load run this function - check the store
// and iterate through nodelist to match saved value and
// node value.
const loadActive=()=>{
let stored=localStorage.getItem( store );
if( stored==null )return;
Array.from( links ).some(a=>{
if( stored==a.href ){
a.classList.add(cn)
return true;
}
});
};
//bind the event handler
links.forEach(a=>a.addEventListener('click',makeActive));
// load active link class
loadActive();
</script>
The link that is clicked will be stored in localStorage
and then when the new page is loaded the loadActive
function will be invoked to set the active
class. As per the comment by @Kiko Software - the default action when clicking a hyperlink would mask any highlighting attempt anyway so the actual setting of the class should be done on page load/reload.
After thinking about the suggestion by @Kiko Software that this could be done with PHP and dispense with Javascript altogether I wrote that as an alternative solution.
The included file playersidenav.php
:
<?php
$cn='active';
$links=array(
'home.php' => 'TEST PAGE HOME',
'news.php' => 'NEWS',
'schedule.php' => 'SCHEDULE',
'partners.php' => 'PARTNERS',
'coaches.php' => 'COACHES',
'tournaments.php' => 'TOURNAMENTS',
'events.php' => 'EVENTS',
'shops.php' => 'SHOPS'
);
?>
<div class="column sidenav">
<div class="row">
<img src="../images/avatar.png" alt="Avatar" />
<h1 style="color:white; float:right; padding-top:7%">Hello John!</h1>
</div>
<?php
foreach( $links as $href => $text ){
printf(
'<a href="%s" class="normal %s">%s</a>',
$href,
( basename( $_SERVER['SCRIPT_FILENAME'] )==$href ? $cn : '' ),
$text
);
}
?>
</div>
And an example page calling said file, called home.php
:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
.sidenav a.active {
background-color: #001F5A;
color: white;
border-radius: 5px;
}
a{margin:1rem;}
</style>
</head>
<body>
<?php
require sprintf('%s/playersidenav.php',__DIR__);
?>
<h1>Hello World!</h1>
</body>
</html>
The PHP include file compares the array key to the basename from the current SCRIPT_FILENAME
server variable and adds the class accordingly and negates the need for Javascript completely. Just proves the old saying - "There's more than one way to skin a cat"
Answer
Solution:
Solution #1
function makeActive(evt) {
var i, normal;
normal = document.getElementsByClassName("normal")
for (i = 0; i < normal.length; i++) {
normal[i].className = "normal"
}
evt.target.className = "normal active"
}
Solution #2
function makeActive(evt) {
var i, normal;
normal = document.getElementsByClassName("normal")
for (i = 0; i < normal.length; i++) {
normal[i].classList.remove('active')
}
evt.target.classList.add("active")
}
Source