I’ve basically got this markup:
<div class="navBar">
<div class="inner blueTheme">
<ul id="" class="navBarMenu">
<li class="xenonActiveMenu blue"><a href="/new_order">Orders</a>
<ul>
<li class="backBtn"><a href="#">< Back</a>
</li>
<li class="xenonActiveMenu "><a href="/new_order">New Order</a>
</li>
</ul>
</li>
<li class="green"><a href="/account_details">Profile</a>
<ul>
<li class="backBtn"><a href="#">Back</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
Jquery:
$('.navBar .inner ul > li').bind('click', function(e){
e.preventDefault();
item = $(this);
if (item.attr('class') != 'selected' && item.attr('class') !='backBtn') {
item.addClass('selected');
var parent = item.parent();
var barWidth = item.width();
var hasSub = item.find('ul').length;
if (hasSub > 0 ){
//Item Does have a submenu
parent.children().each(function(){
$(this).animate({marginLeft: -barWidth}, 400);
});
}
} else {
var parent = $(this).parent().closest('li');
var barWidth = $(this).width();
parent.each(function(){
$(this).animate({marginLeft: barWidth}, 400);
});
}
});
My Problem is, that it thinks the “li” element has been clicked twice, becuase there’s two separate functions for nested LI elements, I just don’t know a way around it, can anyone help?
Shannon
Use
stopPropagation, which does exactly what its name suggests: it prevents the event from bubbling up the DOM tree to the next level of<li>elements.Alternatively, you could separate your handlers to make the code a little more readable, using
$('.navBar .inner > ul > li')for the first level, and$('.navBar .inner > ul > li ul li')for the second.The updated code using
stopPropagationis shown below.