Skip to content
Advertisement

Have multiple links in an ul but only first link is used on click event

I want the user to be able to choose between two links, however, whichever line they select it always runs the first ‘href’.

<div class="ddmenu-container">
   <div class="ddmenu 2">
    United States
    <ul style="z-index: 6">
      <li><a href="https://www.yahoo.com"> E-Commerce Portal </a></li> 
      <li><a href="https://www.google.com"> Website </a></li>
    </ul>
   </div>
</div> 

This is my jQuery code. I assume that it stops running once it finds the first href but I am curious how I can prevent that and allow it to select the second if clicked.

<script type="text/javascript">
  $('.ddmenu.2 ul').click(function(e){
      e.preventDefault();
      window.location = $(this).find('a').attr('href');
  });
</script> 

Advertisement

Answer

Problem:

Well it’s obvious that your code always uses the first link href because of your following code:

$('.ddmenu.2 ul').click(function(e){
   e.preventDefault();
   window.location = $(this).find('a').attr('href');
});

You are attching click to the ul and then you are writing $(this).find('a') so when it finds a matching link(which is the first), it will proceed with it.

Solution:

You need to change your code to attach the click event to li elements or directly to <a> elements, so change your code to:

$('.ddmenu.2 ul li').click(function(e){
   e.preventDefault();
   window.location = $(this).find('a').attr('href');
});

This way when you call $(this).find('a'), it will only fetch inside the clicked li element, so it will get the right link.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement