JQuery.addclass () after loading page

I assign a class to the element, but after loading the page, the class is deleted.

I use this function in my script.js

$('#main-nav li ul li a').click(function(){ $('#main-nav li ul li').children().removeClass('current'); $(this).addClass('current'); }); 

and this is in my view of PHP:

  <ul id="main-nav"> <!-- Accordion Menu --> <li> <a href="#" class="nav-top-item no-submenu"> <!-- Add the class "no-submenu" to menu items with no sub menu --> On site </a> </li> <li> <a href="#" class="nav-top-item current"> <!-- Add the class "current" to current menu item --> Programs </a> <ul> <li><a href="<?php echo site_url('admin/country_management')?>">Manage country</a></li> <li><a href="<?php echo site_url('admin/channel_management')?>">Manage channel</a></li> <li><a href="#">Manage Comments</a></li> <li><a href="#">Manage Categories</a></li> </ul> </li> </ul> <!-- End #main-nav --> 

If I use this <li><a href="<?php echo site_url('...')?>">Manage</a></li> , the class current is added, but after removing the load.

How can I add a class if I use php code after the download page or do you have any solution?

+4
source share
3 answers

with jQuery you can execute the code on page load:

 $(document).ready(function(){ // your code here }); 
0
source

this should work:

 $(document).ready(function(){ $('#main-nav li > a').click(function(e){ $('#main-nav a').removeClass('current'); $(e.target).addClass('current'); }); }); 

if it doesn't work, try this script block before </body> at the end of your document:

 <script type="text/javascript"> $(function(){ $('#main-nav li > a').click(function(e){ $('#main-nav a').removeClass('current'); $(e.target).addClass('current'); }); }); </script> 

this will force execution after html is displayed using php

0
source

First of all, wrap your function in $(document). ready(function () {}) $(document). ready(function () {}) and use the $('#main-nav'). on('click', 'li > a', function () {} ) approach $('#main-nav'). on('click', 'li > a', function () {} ) $('#main-nav'). on('click', 'li > a', function () {} ) inside it. . on() . on() better to attach an event listener to dynamically loaded elements.

0
source

All Articles