Add Class Active When Clicking The Menu Link With Jquery
- Home
-
Solution 1:
I'm also looking for this solution and I have tested your code. On the first approach all links are highlighted and when I click other links it is working properly. The problem was on the home page because all links are highlighted because there is "no event been received" when the page is loaded, the code will work if you send a command or by clicking each links, theoretically. To stop this behavior, I found this code to one of the answers above, add this code and change the ".sibling()" to ".previousSibling()"
$(this).parent().sibling().find('a').removeClass('active');
".sibling()" will highlighted at the end of your links change it to ".previousSibling()" so it will go to first (Li)
$(this).parent().previoussibling().find('a').removeClass('active');
Your code will be like this:
$(function () { var url = window.location.pathname, urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); $('#top a').each(function () { if (urlRegExp.test(this.href.replace(/\/$/, ''))) { $(this).addClass('active'); $(this).parent().previoussibling().find('a').removeClass('active'); } }); });
Solution 2:
Check this , this will only activates clicked tab , remove active for all and then add for the one clicked
$("#top a").click(function() { $('a').removeClass('active'); $(this).addClass("active"); });
Solution 3:
You're running a
foreach
loop on all<a>
tags within your#top
div. So of course it'll add the classactive
to all of them.I think what you're trying to do is this: http://jsfiddle.net/rLddf/4/
I used the
click
event instead.edit switched link to Kristof Feys example - more efficient.
Solution 4:
You may try this out. It will help you:
<script type="text/javascript"> $(function () { $('#sidebar li a').each(function () { var path = window.location.pathname; if (path.indexOf('?') > 0) { var current = path.indexOf('?'); } else { var current = path; } var url = $(this).attr('href'); var currenturl = url.substring(url.lastIndexOf('.') + 1); if (currenturl.toLowerCase() == current.toLowerCase()) { $(this).addClass('active'); var par = $(this).parent(); par.addClass('open'); } }); }); </script>
Solution 5:
try this...
$(function() { $('#yourMenu a').each(function(){ $current = location.href; $target= $(this).attr('href'); if ( $target== $current) { $(this).addClass('active'); } }); });
Post a Comment for "Add Class Active When Clicking The Menu Link With Jquery"