I’d like to use preventDefault on a parent element, but I don’t want it to effect the child elements. Can this be done?
I’ve setup a JsFiddle to help show what I mean:
http://jsfiddle.net/StephenMeehan/FdwST/5/
I’ve been scratching my head over this for a few hours, can’t figure it out…
HTML:
<ul id="SidebarNav">
<li><a href="#">Toys & Games</a></li>
<li><a href="#">Audio Visual</a></li>
<li><a href="#">Electrical</a></li>
<li><a href="#">Photography</a></li>
<li><a href="http://www.google.com">Furniture (Hover over this)</a>
<ul>
<li><a href="http://www.bbc.co.uk">Menu item 1</a></li>
<li><a href="#">Menu item 2</a></li>
<li><a href="#">Menu item 3</a></li>
<li><a href="#">Menu item 4</a></li>
<li><a href="#">Menu item 5</a></li>
</ul>
</li>
<li><a href="#">Music</a></li>
<li><a href="#">Gadgets</a></li>
<li><a href="#">Laptops</a></li>
<li><a href="http://www.google.com">Furniture (Hover over this)</a>
<ul>
<li><a href="http://www.bbc.co.uk">Menu item 1</a></li>
<li><a href="#">Menu item 2</a></li>
<li><a href="#">Menu item 3</a></li>
<li><a href="#">Menu item 4</a></li>
<li><a href="#">Menu item 5</a></li>
</ul>
JavaScript:
// This is my first attempt at writing something useful in jQuery.
$(document).ready(function() {
$("#SidebarNav ul").hide();
$("li:has(ul)").addClass("SubMenu");
// preventDefault removes default events on #SidebarNav a and it's children.
//Is there a way to only target list items with a class of .SubMenu?
// I want to use preventDefault only on .SubMenu a, and still be able to use the links in the drop down menu.
$(".SubMenu a").click(function(e) {
e.preventDefault();
});
// This works, but it sometimes gets confused if there's more than one drop down and the mouse is moved around too fast. Is there a way to force collapse all other SubMenu items on rollover?
$(".SubMenu").on("hover", function() {
$(this).children("ul").delay(100).slideToggle("fast").stop();
});
});
After what I can understand, all you need is to add a
:firstto the.SubMenu aselector to just pick the firstato prevent the default behavior on.So use:
$(".SubMenu a:first").click ....Check out the jQuery documentation on the
:firstselectorEdit: A JS Fiddle for you