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>Item1
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
<li>SubItem2 </li>
<li>SubItem3
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
<li>Item2</li>
<li>Item3
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</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.
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.
If you need the click target to be the LI element (as opposed to Delgan's answer)
you can use .not() over the targeted LI's parents to prevent messing with the bubbling event targets:
$(document).ready(function () {
$('.hmenu').find('li').click(function(event) {
event.preventDefault(); // Prevent page jumps due to anchors
var $par = $(event.target).parents("li"); // get list of parents
$(".hmenu .active").not( $par ).removeClass("active"); // not them
$(this).addClass('active'); // let the event propagation do the work
});
});
$(document).ready(function () {
$('.hmenu').find('li').click(function(event) {
event.preventDefault();
var $par = $(event.target).parents("li");
$(".hmenu .active").not($par).removeClass("active");
$(this).addClass('active');
});
});
.active > a{
background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu1" class="hmenu">
<ul>
<li>Item1
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
<li>SubItem2 </li>
<li>SubItem3
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
<li>Item2</li>
<li>Item3
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
</ul>
<br style="clear: left" />
</div>
To better understand the above
The following example works out-of-the-box, and the clicked one and all it's LI parents get the "active" class.
Why? Cause the event target is li, means any li of .hmenu - so that click is attached to any of them, and clicking the subsub LI the event will propagate to the LI parents - triggering the same click behavior (this add class)!
$(".hmenu").on("click", "li", function(){
$(this).addClass("active"); // Wow! Event propagation rulez!!
});
But we need to remove existing .active and here it gets messy...
$(".hmenu").on("click", "li", function(){
$(".active").removeClass("active"); // triggered on every event bubble :(
$(this).addClass("active"); // leaving only the main parent with active class
});
That's caused by the concurrency that happens while the event bubbles and triggers the same actions for the parent elements.
One way to prevent that concurrency would be using a setTimeout of 1ms:
$(".hmenu").on("click", "li", function(){
$(".active").removeClass("active");
setTimeout(function(){ // Let the previous finish the bubbling mess
$(this).addClass("active"); // Yey! all fine! Every LI has the active class
}, 1);
});
But here the timeout of 1ms can lead to visual "blinking" issues.
Try this:
$(function () {
$("li a")
.on("click", function () {
$(this).toggleClass("active");
$(this).closest("ul").parent().children("li a").toggleClass("active")
.parent().parent().parent().children("li a").toggleClass("active");
});
});
fiddle
Traverse from the clicked element. And use toggleClass() to avoid the mundane checking if hasclass removeClass ...
Related
I have this code
<script>
$("li").hover(
function () {
$(this).addClass('active');
},
function () {
$(this).removeClass('active');
}
);
</script>
In order to add class active to my li in a menu.
<ul class="list-first-level">
<div about="" typeof="" class="ds-1col entity entity-paragraphs-item paragraphs-item-modulo-de-enlaces-item view-mode-modulo_de_enlaces_01_d clearfix">
<li id="elm" class="active always">
Undergraduate programmes
<ul>
<li>
Law
</li>
</ul>
</li>
</div>
</ul>
I need to not remove the active class after Im not hover on the element.
Just use this:
$("li").hover(function(){
$(this).addClass("active");
});
Although, you will end up with many active LI and does not provide a good UX.
When you hover over an element, remove the 'active' class from all li elements then add it back to the current element. This still means that if the user moves away from the last, hovered element - that element will remain in an 'active' state.
<script type="text/javascript">
$("li").hover(
function () {
$("li").removeClass('active');
$(this).addClass('active');
}
);
</script>
I have a page with a list of menu items consisting of internal anchors. I'm trying to add an .active class to the selected item. It seems to work on load but when clicking a new item in that same page it doesn't.
When clicking a new menu item, I would like to remove all other active classes and add this class to the clicked item.
Sounds pretty simple, but I can't make it work.
I created this Fiddle, but it doesn't show the issue correctly, since I can't add hashes to the url.
However, maybe someone can point me in the right direction.
JS:
function setActiveLinks() {
var current = location.pathname;
$('.bs-docs-sidenav li a').each(function() {
var $this = $(this);
// Get hash value
var $hash = location.href.substr(location.href.indexOf('#') + 1);
if ($this.attr('href') == '#' + $hash) {
$this.parent().addClass('active');
}
})
}
setActiveLinks();
$('#leftmenu li a').click(function() {
$('#leftmenu li').removeClass('active');
setActiveLinks();
});
HTML:
<ul class="nav bs-docs-sidenav">
<li>
Download
</li>
<li class="active">
What's included
<ul class="nav">
<li class="active">Precompiled</li>
<li>Source code</li>
</ul>
</li>
<li>
Compiling CSS and JavaScript
<ul class="nav">
<li>Installing Grunt</li>
<li>Available Grunt commands</li>
<li>Troubleshooting</li>
</ul>
</li>
</ul>
Thanks. :-)
You have wrong selector to bind click event on anchor element. also you don't need to call setActiveLinks() function(which sets class based on href) here.
You can use context of clicked anchor element to traverse to parent li and add class active in it:
var $navLIs = $('.nav li')
$navLIs.find('a').click(function() {
$navLIs.removeClass('active');
$(this).parent().addClass('active');
});
Working Demo
I have been trying to make -just- the first child of: ".accordion-media-types a" to work.
At the moment, every anchor is toggling and grabbing the style of ".accordion-media-types" while they should be a regular looking link, so I just need the first one to work, is it possible somehow?
http://jsfiddle.net/0mpuh2f2/8/
html:
<ul class="accordion-media-types">
<li>
Info
<div class="hidden-content">
<ul>
<li>
link
</li>
</ul>
</div>
</li>
</ul>
js:
$(document).on('click', '.accordion-media-types a', function (e) {
e.preventDefault();
$(this).closest('.accordion-media-types').toggleClass('active').find('.hidden- content').slideToggle(500);
});
thanks in advance for any help!
You can use direct child selector: .accordion-media-types > li > a:
$(document).on('click', '.accordion-media-types > li > a', function (e) {
e.preventDefault();
$(this).closest('li').toggleClass('active').find('.hidden-content').slideToggle(500);
});
Read about child selectors here.
Also note that you probably want to toggle only closest li hidden content, not all of them at once.
Demo: http://jsfiddle.net/0mpuh2f2/11/
I'm working with the off-canvas script from Foundation and it isn't working out of the box (of course) when I try to use the submenu options. I realized it wasn't adding a class (move-right) to the ul's of the li's in the off-canvas navigation. So I wrote a script to add that class which can be found here:
jQuery(document).ready(function() {
jQuery('ul.off-canvas-list li a').click(function() {
jQuery('ul.off-canvas-list li ul.left-submenu').addClass('move-right');
});
});
And here is how my HTML is structured:
<ul class="off-canvas-list">
<li class="has-submenu">Name 1
<ul class="left-submenu">
<li class="back">Back</li>
<li><a href="#"></li>
<li><a href="#"></li>
</ul>
</li>
<li class="has-submenu">Name 2
<ul class="left-submenu">
<li class="back">Back</li>
<li><a href="#"></li>
<li><a href="#"></li>
</ul>
</li>
<li class="has-submenu">Name 3
<ul class="left-submenu">
<li class="back">Back</li>
<li><a href="#"></li>
<li><a href="#"></li>
</ul>
</li>
...etc
</ul>
My problem is that my script is adding the class to ALL ul.left-submenu's instead of just the one directly under the li that I click on. I can't figure out how to add the class 'move-right' to only the 'ul.left-submenu' child of the parents li that I clicked on and remove the 'move-right' class from the other 'ul.left-submenu'
I thought maybe using the sibling() selector, but I wasn't quite sure how to implement that into my script. Any and all help is greatly appreciated.
Another issue has arose and that is being able to close the opened "ul.left-submenu" by clicking on the "Back" which comes before the other li's in each ul.left-submenu. I updated the HTML above to include the "" and also have provided the script below that I tried using that hasn't worked.
jQuery('li.back').on('click', function() {
console.log('close submenu');
jQuery('ul.left-submenu').removeClass('move-right');
});
The target element is the grandparent of the clicked element so you can use the closest method:
$('ul.off-canvas-list li a').click(function() {
$('.move-right').removeClass('move-right');
$(this).closest('ul.left-submenu').addClass('move-right');
});
you can add it directly to the clicked element by using this
jQuery(document).ready(function() {
jQuery('.left-submenu li a').click(function() {
jQuery('.left-submenu').removeClass('move-right'); // remove class move-right from every elements with class left-submenu
jQuery(this).parents('.left-submenu').addClass('move-right'); // add class move-right to the parent with class left-submenu of current element
});
});
Edit:
if in your updated code, you want to click only by a right after .has-submenu, you need this probably, so it didn't trigger on click for a inside .left-submenu
jQuery(document).ready(function() {
jQuery('.has-submenu > a').click(function() {
jQuery('.left-submenu').removeClass('move-right'); // remove class move-right from every elements with class left-submenu
jQuery(this).children('.left-submenu').addClass('move-right'); // add class move-right to the children with class left-submenu of current element
});
});
sorry for my mistakes not looking again for the code before posting it, because ul.left-submenu is in the same position with a and not it's children, you need to use .siblings to get ul.left-submenu, so change the code to this
jQuery(document).ready(function() {
jQuery('.has-submenu > a').click(function() {
jQuery('.left-submenu').removeClass('move-right');
jQuery(this).siblings('.left-submenu').addClass('move-right');
});
});
here's the working Example in Fiddle
Ok, so you want to add a class move-right to the ul.left-submenu that is directly under the has-submenu li that you clicked, right?
So:
$(document).ready(function() {
//Trigger the click only on the li's has-submenu
$('li.has-submenu').on('click', function() {
//Remove the class from other ul, if there's any
$('ul.left-submenu').removeClass('move-right');
//Finds the direct ul child using the '>' selector, and adds the class.
$(this).find('> ul.left-submenu').addClass('move-right');
});
});
The way you have your selector it targets all the ul.left-submenu elements you have, another way to target just the element clicked would be like this:
$('.off-canvas-list').on('click', 'ul.off-canvas-list li a', function (){
$('.move-right').removeClass('move-right');
$(event.target).closest('ul.left-submenu').addClass('move-right');
});
Your selector is too broad. If what you want to do is to add move-right to left-submenu when you click has-submenu, that's what you need to do:
$('.has-submenu').click(function() {
$(this).find($('.left-submenu')).addClass('move-right');
});
Fiddle: http://jsfiddle.net/x9zcav0p/
If you need to reset move-right, do this:
$('.has-submenu').click(function() {
$('.move-right').removeClass('move-right');
$(this).find($('.left-submenu')).addClass('move-right');
});
Fiddle: http://jsfiddle.net/x9zcav0p/1/
Updated markup:
For your updated markup, you can target the next() element after the anchor tag:
$('.has-submenu > a').on('click', function() {
$('.move-right').removeClass('move-right');
$(this).next().addClass('move-right');
});
Fiddle: http://jsfiddle.net/x9zcav0p/2/
I have the following code structure:
<ul class='menu'>
<li>
Main Menu
<ul class='hide'>
<li>SubMenu1</li>
<li>SubMenu2</li>
</ul>
</li>
<li>
Main2
<ul class='hide'>
<li>Sub1</li>
</ul>
</li>
</ul>
Is there a way for me to have a jQuery click event on Main Menu and Main2 in a generic way that will remove the class 'hide' of the correct children each time?
Here is another way, which uses event delegation and only runs when the li element and not its children was clicked:
$('ul.menu').on('click', 'ul.menu > li', function(e) {
if(e.target === this) {
$(this).children('ul').toggleClass('hide');
}
});
DEMO
$("ul.menu > li").on("click", function () {
$(this).children("ul").removeClass("hide");
});
Example: http://jsfiddle.net/dpkBL/
Dont always do what the crowd tells you, at least think about it for a while!
I bet people will recommend you to use a selector such as ul.menu > li, but please remember that this will not only trigger a click event when you click on the text "Main Menu", but also when you click on any of the other content inside the matching li.
If you'd like to implement a show/hide toggle you are far better off wrapping the text "Main Menu" inside it's on element, and then use something as the below to alter what you may want to alter.
$(<main menu text selector>).siblings (<siblings selector>);
Still want/have to follow the crowd?
If this is the case I'd recommend you to at least do it with a little twist to prevent what I previously described.
(edit: revised version after reading the jquery documentation for elements)
$('ul.menu > li').click (function(e){
if (e.target === this) {
$(this).children ('.hide').removeClass ('hide');
}
});
$("ul.menu > li").click (function () {
$(this).find ('.hide').removeClass ('hide');
});
$("ul.menu > li > *").click (function () {
return false; // prevent event from bubbling up
});
Sample implementation of recommended version
The below will bind a click-event-listener to .menu-toggle, when the event is fired the siblings (ie. the tags who are in the same scope as the clicked .menu-toggle) matching .hide will have their class="hide" removed.
Javascript
$(".menu-toggle").click (function () {
$(this).siblings ('.hide').removeClass ('hide');
});
HTML
<ul class='menu'>
<li>
<span class="menu-toggle">Main Menu</span>
<ul class='hide'>
<li>SubMenu1</li>
<li>SubMenu2</li>
</ul>
</li>
<li>
<span class="menu-toggle">Main2</span>
<ul class='hide'>
<li>Sub1</li>
</ul>
</li> </ul>
Take a look at the child selectors. I think that is what you want.
$('.menu > li').click(function () {
$(this).children('ul').removeClass('hidden');
});