Css added with addclass not working on page load
I have a menu 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 the current page link to be active in the menu. Therefore, I use the addclass method.
$(".menu ul li a").click(function() { $(".menu ul li a").removeClass('selected'); $(this).addClass('selected'); }); All of these codes are on the header.html page, which is my header file. I am including this page using php on all other pages.
The problem is that when I click on the menu links addclass works, but by the time the page loads (on the href page) addclass's css will not work. Can anyone help solve the problem?
Thanks to everyone.
Solved the problem. I have included addclass on all pages, otherwise it will not work on loading.
In the header.php file, I assigned the current page URL to the page variable so that on any pages that contain the header file, the page variable is available.
$(document).ready(function(){`<br/> if(page=="localhost/workspace/pjt/aboutus") {` <br/> $(".menu ul li a").removeClass('selected');` <br/> $(".menu ul li a#about").addClass('selected'); } }); Do you use a document method? If not, this is your problem. The DOM does not load fully when you execute jQuery code. Run your code as follows:
$(function(){ $(".menu ul li a").click(function() { $(".menu ul li a").removeClass('selected'); $(this).addClass('selected'); }); }); ... or ... just execute your code in the script tag at the bottom of the page (right before the closing tag).
Like the side of node:
$(function() {}); not suitable for
$(document).ready(function(){ ... }); Try under the document. Already like
$(document).ready(function(){ $(".menu ul li a").click(function() { $(".menu ul li a").removeClass('selected'); $(this).addClass('selected'); }); //Here defaulty add class for first link on page load like $(".menu ul li a:eq(0)").addClass('selected'); }) It is better to do this in server-side code, but it is possible to do this on the client side. You should get the current page address, and then select your link based on this:
$(function () { // get the current page var link = window.location.href.split('/'); page = link[link.length - 1]; // now select the link based on the address $('.menu ul li a[href*="' + page + '"]').addClass('selected'); });