Reputation: 678
i have an unordered list as a left nav with quite a few links in it. most of the list items have another unordered list as a submenu associated with them. however, a few of the links have no submenus. i want to disable the default click behavior on the links that have submenus so i can have the submenu animate open. but on the links with no submenu i need to have the link clickable. the javascript i have to do this is:
$(function(){
if($("#leftNav ul:first > li > a").siblings().size() > 0){
$("#leftNav ul:first > li > a").click(function(e){
e.preventDefault();
});
}
the problem is that this disables the default click behavior for all the links, not just the ones with siblings. the html for the left nav looks like this
<div id="leftNav">
<ul>
<li>
<a href="#">Link 1</a>
<ul>
<li><a href="#">Submenu Link 1</a></li>
<li><a href="#">Submenu Link 2</a></li>
<li><a href="#">Submenu Link 3</a></li>
</ul>
</li>
<li><a href="#">Link 2</a></li>
</ul>
</div>
so the click behavior would need to be removed on Link 1 because it has the <ul>
as a sibling. Link 2 has no siblings so it should be left alone.
Upvotes: 2
Views: 7465
Reputation: 11
I don't have a high enough reputation score to comment, but just wanted to say that Chuck's answer worked perfectly for me (EXCEPT IN FIREFOX?). My menu also hides other open menus before opening the one you have clicked - here's the code I used:
jQuery(document).ready(function($) {
$('ul.menu li ul.sub-menu').hide(); //Hide children by default
$("ul.menu:first > li > a").not(":only-child").click(function(){
event.preventDefault();
$(this).parent().siblings().children('ul.menu li ul.sub-menu').css('display','none');
$(this).siblings('.sub-menu').slideToggle(800);
});
});
Upvotes: 1
Reputation: 82933
<script type="text/javascript">
$(function () {
$("#leftNav ul:first > li > a").each(function (a, b) {
var t = $(b);
//alert(t.siblings().size() );
if (t.siblings().size() > 0) {
t.click(function (e) {
e.preventDefault();
});
}
});
});
</script>
Upvotes: 3
Reputation: 237080
Simplest way:
$("#leftNav ul:first > li > a").not(":only-child").click(function(e){
e.preventDefault();
});
Upvotes: 3
Reputation: 253396
One way to do it is to find those li
elements that have a descendant ul
, and in that li
find the a
and target those:
$('#leftNav li:has("ul")').find('a').each(
function(){
$(this).click(
function(){
alert("No clicking here");
return false;
});
});
Edited to add a revised jQuery:
$('#leftNav li:has("ul")').find('a').each(
function(){
$(this).click(
function(){
alert("No clicking here");
return false;
});
});
$('#leftNav li:has("ul")').hover(
function(){
$(this).find('ul').slideDown();
},
function(){
$(this).find('ul').slideUp();
});
Slightly more useful JS Fiddle demo.
Upvotes: 4