I have a boostrap navbar in my pages, the inside content I have placed in another file, nav01.php, because I used to change it a lot and wanted to have it in a separate single file. The question is, I want to have the same file for all pages, and yet I'd like to mark the current page as active if possible in the navbar.
When I had the navbar code in every page, it worked, but as soon as I moved it to a seaparate file, and read it with the jquery load method into every page, it isn't working. The file loads good, but the code I used for marking the current page as active does not work anymore, does nothing.
This is the content inside my navbar, nav01.php:
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href='home.php'><span class="glyphicon glyphicon-home"></span></a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li><a href='documentation.php'>Documentation</a></li>
<li><a href='admin.php'>Admin</a></li>
<li><a href='login.php'>Login</a></li>
</ul>
</div>
</div>
This is the script that worked prior to moving to new file:
<script type="text/javascript">
$(document).ready(function () {
$("li a[href='" + location.href.substring(location.href.lastIndexOf("h/") + 1, 255) + "']").parent().addClass("active");
});
</script>
This is the load call I use for writing the nav01.php into every other php page:
$(document).ready(function(){
$("#nav01").load("nav01.php");
});
Simply load call inside script/script.js
The php files only have the nav with the id, my script loaded at the bottom:
<nav class="navbar navbar-inverse" id="nav01"></nav>
<script src="script/script.js"></script>
If I understand it, the problem is, I'm trying to use a jQuery code, client side, in a php page, the server executes and then load "as it is" ? When I load the page, it cannot be changed anymore, because the code isn't there in that php page that calls ? The script code inside nav01 efectively gets current location, but when it's executed, it's inside nav01 page, so no page is active so it does nothing?
I have been looking for a lot of answers here, but none was in my situation, and I have not been able to figure out a solution, $_SERVER['REQUEST_URI'] php will only give me nav01.php, and I don't know if I can send a GET variable via the jQuery load method with the address of the page where the nav is going to be inserted.
Thanks.
The ready jQuery event only fires once, when the DOM content is ready. What I would recommend is put your active element marking function in the load function's callback like:
$("#nav01").load("nav01.php", function() {
$("li a[href='" + location.href.substring(location.href.lastIndexOf("h/") + 1, 255) + "']").parent().addClass("active");
});