Highlight current url in menu with jquery

I have a menu, but I want to highlight the current link with jquery.

var loc = window.location; var lochref = $("#topNavigation li a").attr("href"); if(lochref == loc){ $('#topNavigation li a').addClass('currenthover'); } 

There are no changes to the script in class "a". How can I do this using jquery? thanks in advance

+4
source share
4 answers

First: This is what you should consider server-side. It is much, much, much simpler and more reliable.

In your code, only the href of the first link is compared, since attr returns the property value of the first link. You need to iterate over the links to find the right one.

 var loc = window.location.href; $("#topNavigation li a").each(function() { if(this.href == loc) { $(this).addClass('currenthover'); } }); 
+3
source

I would either log loc and lochref in the console, or make a warning to find out what these values ​​are, it can be as simple as skipping the trailing slash. In addition, the code is valid.

http://jsfiddle.net/loktar/gjZVK/3/

hit mileage and the second warning should match and the link will turn red.

+1
source

I always used jQuery to highlight the current menu item. Try the following:

 $(function () { var loc = window.location; var pathName = loc.pathname.substring(loc.pathname.lastIndexOf('/') + 1); $('[href$="' + pathName+ '"]').parent().addClass("active"); }); 
+1
source

You missed .href from the window.location object. You need to change the first line to:

 var loc = window.location.href 
0
source

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


All Articles