I have been making a website that has lots of pages. Hence decided to put the navigation bar in a separate php file to reduce re-work in all those pages in case of changes. So in my index.php
I have included the navigation bar like:
<?php include 'navbar.php'; ?>
And the navbar.php looks like:
<div id="nav">
<ul>
<li pg="#home" >home</li>
<li pg="#pack" >packages</li>
<li pg="#about" >about</li>
</ul>
</div>
In the index.php, I have a javascript onClick function to select the <li>
from navbar:
<script type="text/javascript">
var oldpg = "#home";
$(document).ready(function() {
$('#nav ul li').click(function() {
//here are the codes to hide/show divs });
});
</script>
But when you click those <li>
nothing happens. I think the js is not picking up the elements from the php. How can I refer to those elements in a separate php file?
Use on
and try. Not tested but that may be the problem here. Try
$(document).ready(function() {
$(document).on('click', '#nav ul li', function(e) {
//Your code
});
});
Also make sure that you included jQuery
library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
The code you showed us is correct. As long as the div
with id "nav" is indeed being displayed, make sure you are including the jQuery library correctly. If it is, your error must reside inside whatever you did inside the click event handler $.click
(in //here are the codes to hide/show divs
).
You need to fix your JavaScript:
$(document).ready(function() {
$('#nav ul li').click(function() {
//here are the codes to hide/show divs });
});
}); // you left off this closing
You can use Chrome DevTools or Firebug to view the console.
Thanks for replying @Retsam @Campari @Chris @Ankit
As @Retsam said, I tried with Chrome console and found the error to be Uncaught reference error: $ not defined
(Firebug console didn't give any error/message) The reason was because I had put my code before linking with the jQuery library. So I moved my
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
above the onClick
function and it worked.
Silly me ...
Thanks guys