How to use preventDefault() for parent item only in a menu?

3k views Asked by At

I'm building a menu with touch based drop downs and everything's working great, except, when a person clicks the parent, I want it only to activate the drop down and not go to the link listed in the parent's href. So, I've tried using preventDefault() but it's also disabling the link for all the children in the drop down. I only want it to disable the link for the parent and allow the children's link to work normally. How do I use it to just target the parent's link. Here's my code:

Menu

<ul class="nav menu">
 <li class="parent"><a href="#">Parent</a>
  <ul class="nav-child">
    <li><a href="#" >Child 1</a></li>
    <li><a href="#" >Child 2</a></li>
    <li><a href="#" >Child 3</a></li>
  </ul>
 </li>
</ul>

jquery

var $dropDownLinks = $('.parent a');

$dropDownLinks.click( function(event){
   event.preventDefault();
});
1

There are 1 answers

0
Queli Coto On BEST ANSWER

What you can do is limit your element selector:

Try selecting only the direct child element of .parent.

this can be done with ">", sample

var $dropDownLinks = $('.parent > a');

$dropDownLinks.click( function(event){
   event.preventDefault();
});