Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: preventDefault on parent link only

SOLUTION:

Found a solution.

Used parentNode:

$('.skaftetopmenu-li > a').click(function(e) {
   e.preventDefault();
   var subid = $(this.parentNode).attr('id');
   if (subid !="forsidemenu"){
      var str = $('#submenu-content-'+subid).html();
      if ($.trim(str) == ""){
         $('.submenu-content', this.parentNode).load('http://' + skafte.base_url + '/inc/top-menu-subs/'+subid+'_submenu.html');
      }
   }
});

I have a menu like this:

<ul>
  <li class="parent">
    <a href="url">Link title parent</a>
    <ul>
      <li><a href="url">Link title child</a></li>
    </ul>
  </li>
</ul>

I have tried the following in jQuery:

$('.parent').click(function(e) {
  e.preventDefault();
});

However this disables all the elements in the whole menu structure. I want to only disable the parent links. The ones in "ul li", and not the links in "ul ul li", but I can't figure out how and I have searched and searched. So please help me out!


EDIT: Thank you for the answers. I thought I would simplify my code in the question but that actually didn't benifit me. So heres the actual code I'm using:

$('.skaftetopmenu-li').click(function(e) {

   var subid = $(this).attr('id');

   if (subid !="forsidemenu"){

      var str = $('#submenu-content-'+subid).html();

      if ($.trim(str) == ""){

         $('.submenu-content', this).load('http://' + skafte.base_url + '/inc/top-menu-subs/'+subid+'_submenu.html');
      }
   }
});

And the HTML:

<li class="skaftetopmenu-li" id="priser">
   <a href="http://<?php echo DOMAIN?>/priser.php">Priser &amp; Sortiment</a>
   <div class="submenu-content" id="submenu-content-priser"></div>
</li>

If I try to do as you suggest and set it to:

$('.skaftetopmenu-li > a').click(function(e) {
   e.preventDefault();

It doesn't work..

like image 314
user2171247 Avatar asked Feb 17 '23 04:02

user2171247


1 Answers

Similar to Austin Mullins' answer, I think you want this:

$('li.parent > a').click(function(e) {
    e.preventDefault();
});
like image 128
Jacob VanScoy Avatar answered Mar 04 '23 19:03

Jacob VanScoy