Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  134] [ 3]  / answers: 1 / hits: 22728  / 9 Years ago, sat, june 27, 2015, 12:00:00

I have searched a lot for adding active class to the parent menu using javascript.



I found many more examples but not a single one is working for me, below is my code



HTML



<div id=menu1 class=hmenu>
<ul>
<li><a href=#>Item1</a>
<ul>
<li><a href=#>SubItem1</a>
<ul>
<li><a href=#>SubSubItem1</a></li>
<li><a href=#>SubSubItem2</a></li>
</ul>
</li>
<li><a href=#>SubItem2</a> </li>
<li><a href=#>SubItem3</a>
<ul>
<li><a href=#>SubSubItem1</a></li>
<li><a href=#>SubSubItem2</a></li>
</ul>
</li>
</ul>
</li>
<li><a href=#>Item2</a></li>
<li><a href=#>Item3</a>
<ul>
<li><a href=#>SubItem1</a>
<ul>
<li><a href=#>SubSubItem1</a></li>
<li><a href=#>SubSubItem2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<br style=clear: left />
</div>


My requirement is when i click on SubItem1 then both Item1 and SubItem1 should be active.



And when i click on SubSubItem1 then SubSubItem1 ,SubItem1 and Item1 should be active.



Means when click on any link then its all parent link and the same link should be active.



I have tried with this javascript code :



$(document).ready(function () {
$('.hmenu ul li ul').find('li').click(function () {
//removing the previous selected menu state
$('.hmenu').find('li.active').removeClass('active');
//adding the state for this parent menu
$(this).parents('li').addClass('active');
});
});


Actually i don't have any experience with javascript coding and unable to figure out the problem in my code.



Can anyone suggest me for the same.


More From » html

 Answers
20

The issue comes from .find('li').click().



As you use nestsed <li>, this will cause the event to be fired two times when you click on a child <li>. This causes problems. Can not you add the click() to <a> elements?



$(document).ready(function () {
$('.hmenu a').click(function () {
//removing the previous selected menu state
$('.hmenu').find('li.active').removeClass('active');
//adding the state for this parent menu
$(this).parents(li).addClass('active');

});
});


It works just fine: https://jsfiddle.net/6put8tdx/






Note that your page will be bumped to the top while clicking to a tab because of # anchor. If you want to prevent this, you may pass the event to the function .click(function (event) {...} and add event.preventDefault inside.


[#66023] Thursday, June 25, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
milor

Total Points: 284
Total Questions: 93
Total Answers: 115

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
;