'How to stop event propagation to other elements with the same class?

I have written this function that binds to a button, which when clicked toggles the class to provide a dropdown. The only problem is is that I have multiple buttons on the same page that have the same functionality, and they all fire when one is clicked:

app.bind.DirectionDropdown = function(){
    $('.direction-button').bind('click', function(){
        $('.direction-dropdown').toggleClass('active');
    });
    
};

Here is the HTML:

<div class="contact-card">

      <div class="contact-directions">
        <ul class="contact-directions-items">
          <li class="map-pin contact-directions-item"><a href="#"><span class="fa fa-map-marker"></span></a></li>
          <li class="contact-directions-item"><p>3700-1 Place Ville Marie</p></li>
          <li class="contact-directions-item"><p>Montreal, Quebec</p></li>
          <li class="contact-directions-item"><p>H3B 3P4 Canada</p></li>
        </ul>
        <a href="#" title="#" class="link-button direction-button animate-after">Directions</a>
      </div><!-- end .contact-directions -->

    </div><!-- end .contact-card -->

    <div class="direction-dropdown fade-in">
    
      <h4>Direction on how to get here...</h4>

      <a href="#" class="link-button direction-button">Close</a>

        <!-- content --> 

    </div><!-- end .direction-dropdown -->

How can I edit this function to fire only on the one button clicked, and not the others?



Solution 1:[1]

The event is not propagated to the other buttons, but inside the click event you select all buttons again. Use this to only select the button that was clicked.

app.bind.DirectionDropdown = function(){
    $('.direction-button').bind('click', function(){
        $('.direction-dropdown').removeClass('active');
        $(this).parent().addClass('active');
    });
};

Or, if you want to be able to close the menu by clicking the same button again:

app.bind.DirectionDropdown = function(){
    $('.direction-button').bind('click', function(){
        // Remove the class from all others, excluding the clicked one.
        $('.direction-dropdown').not($(this).parent()).removeClass('active');
        // Toggle for the clicked one.
        $(this).toggleClass('active');
    });
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1