Class does not work on page

I know that this question is met a lot, but I just can’t understand how to do this, using already reply messages. Here I have different menus on the same page. When I click on each menu, I want this menu to be active, but it does not work here.

This is my view page:

<ul class="nav navbar-nav navbar-right"> <li class="active"> <a class="page-scroll" href="<?php echo base_url();?>nowaste_control/index#about">About</a> </li> <li class=""><a class="page-scroll" href="<?php echo site_url('nowaste_control/index#product'); ?>">Products</a> </li> <li class=""> <a class="page-scroll" href="<?php echo base_url();?>nowaste_control/index#technology">Technology</a> </li> </ul> 

This is my jQuery:

 <script type="text/javascript"> $('.nav navbar-nav li a').click(function($) { $('a[href="'+window.location.pathname+window.location.hash+'"]').parent().addClass('active'); }); </script> 
+5
source share
3 answers

Here is an example way to do this. By the way. since I cannot have a html code snippet for the navigation list, I just created a simple

html i created here

 <div class="nav"> <li class="active"> <a class="page-scroll" href="#about">About</a> </li> <li class=""><a class="page-scroll" href="#product">Products</a> </li> <li class=""> <a class="page-scroll" href="#technology">Technology</a> </li> </div> 

here is javascript

 $(document).ready(function(){ $(document).on('click', '.nav li a', function () { console.log($(this)); $('.active').removeClass('active'); $(this).parent().addClass('active'); }); }); 

Demo

+4
source

Try to execute

 $(function(){ $('.page-scroll').on('click',function(){ $('.active').removeClass('active'); $(this).parent().addClass('active'); }); }); 

use this to activate the active class when loading the page:

 $(function(){ $('.active').removeClass('active'); $('a[href="'+window.location.href'"]').parent().addClass('active'); }); 
0
source

Try the following: you can wrap your script in $(function(){..}); to ensure that the DOM is ready. You also need to fix your jquery selector, because according to class="nav navbar-nav navbar-right" your selector should be .nav.navbar-nav , not .nav navbar-nav (this means that inside nav there is a child navbar-nav ). See below code

 $(function(){ //here instead of ".nav navbar-nav" change it to ".nav.navbar-nav" $('.nav.navbar-nav li a').click(function($) { $('a[href="'+window.location.pathname+window.location.hash+'"]').parent().addClass('active'); }); }); 

And if you dynamically create these elements, use .on() as shown below -

 $(function(){ //here instead of ".nav navbar-nav" change it to ".nav.navbar-nav" $(document).on('click','.nav.navbar-nav li a',function($) { $('a[href="'+window.location.pathname+window.location.hash+'"]').parent().addClass('active'); }); }); 
0
source

Source: https://habr.com/ru/post/1247096/


All Articles