Generalize a Javascript dropdown function?

Asked

Viewed 90 times

0

Hello, I’m having a certain difficulty to generalize a dropdown function, I imagine I’m doing something very wrong, I searched on forums and did not find the answer so I’ll open this topic.

My code HTML is like this, there are several buttons with the same classes but I want each one to dropdown only to their respective menu:

<a class="sb-dropdown-toggler" href="#" style="border-color: #05204A">
  <i class="fas fa-wrench sb-icon-size"></i><i class="fas fa-caret-down"> 
</i><span>Ferramentas</span>
</a>
<div class="sb-dropdown-menu">
  <a href="#">Action</a>
  <a href="#">Another action</a>
  <a href="#">Something else here</a>
</div>

The CSS thus:

.sb-dropdown-menu{
    display: none;
}
.sb-dropdown-menu.dropdown-active{
    display: block;
}

And the Javascript thus:

$('.sb-dropdown-toggler').each(function () {
    $(this).click(function (e){
      e.preventDefault();
      $(this + ' .sb-dropdown-menu').toggleClass("dropdown-active");
    });
  });

My intention is to have the submenu of each button activated only by your "father", is it possible to do this the way I am doing? Do I have to add or remove anything? I tried several ways and could not, I imagine I have to add an ID to each but I do not know how to do it, I appreciate the help of anyone who can

  • How the link relates to the dropdown?

  • They are brothers (they are in the same div, separated from others), it is always one after the other....

  • And do you have several of these blocks in sequence? You usually use lists for this. Anyway, your function should work minimally if you use $(this).next('.sb-dropdown-menu'), instead of $(this + ' .sb-dropdown-menu') that is wrong.

  • That’s exactly what it was @bfavaretto, thank you!

  • Cool that solved!

1 answer

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.