after searching through the question and replies I still cannot get the NAVBAR to add class "active" on the current page.
$(document).ready(function () {
$(".nav-link").on("click", function(){
$(".nav-link").find(".active").removeClass("active");
$(this).parent().addClass("active");
});
});
I do see the class added and when the new page load the class is gone..?? i cannot understand this jquery.
the work around that I have found is to provide variable
<?php pageID = "index"; ?>
on each page and in the respective 'nav-link' a class
<?php echo(pageID=="index") ? "active" : "" ?>
btw the navbar code is in the header.php which is loaded on each page include('header.php');
looking for guidance on how to use the jquery instead of work around
Your workaround is, in fact, the typical way to achieve this. Javascript will not persist the changes it did through your navigation. To achieve want you want to do in JS, you probably want to use localStorage
/* Sample code */
localStorage.setItem('activeMenu', 'blog');
$(function(){
if (localStorage.getItem('activeMenu') === 'blog') {
$('#blogNavLink').addClass('active');
}
}
If you want to do it in PHP, you could probably use a PHP variable or a hidden input that would contain the selector and use it in JS.
$activeMenu = 'blog';
<input type="hidden" id="menuItem" value="<?= $activeMenu ?>">
$(function(){
if ($('#menuItem').val() === 'blog') {
$('#blogNavLink').addClass('active');
}
}