Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css added with addclass not working when page is loaded

Tags:

jquery

css

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?

like image 694
Jenz Avatar asked Feb 17 '23 11:02

Jenz


1 Answers

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(){ ... });
like image 83
Bas Slagter Avatar answered Feb 19 '23 03:02

Bas Slagter