I have a menubar with the following links.
<div class="menu">
<ul>
<li><a href="aboutus.php" onclick="changecss(1)">About Us</a></li>
<li><a href="services.php" onclick="changecss(2)">Services</a></li>
<li><a href="career.php" onclick="changecss(3)">Career</a></li>
<li><a href="contactus.php" onclick="changecss(4)">Contact Us</a></li>
</ul>
</div>
I want to make current page link active in the menubar. So I am using addclass
method..
$(".menu ul li a").click(function()
{
$(".menu ul li a").removeClass('selected');
$(this).addClass('selected');
});
All these codes resides in header.html page which is my header file.I am including this page using php in every other pages.
The problem is that when I click on the menubar links, the addclass
is working but by the time the page is loaded(to the href
page), the addclass's
css wont work. Can anyone help to fix the problem?
Do you use the document ready method? If not, there is your problem. The DOM is not fully loaded when you execute your jQuery code. Execute your code like this:
$(function(){
$(".menu ul li a").click(function() {
$(".menu ul li a").removeClass('selected');
$(this).addClass('selected');
});
});
...or...just execute your code in a script tag at the bottom of your page (right before the closing body tag).
As a side node:
$(function() {});
is short for
$(document).ready(function(){ ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With