Ad

Hiding/Showing Divs On Click

- 1 answer

I have created a script that when a button is clicked it displays all of the content beneath it and hides the other buttons content. The only problem I'm having is that I want to refactor the script so it only works if you hit the button, instead of the entire div the button sits in as it's causing some confusion. What would be the best way about this?

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

<div class="signup-button">
  <button type="button" class="btn btn-default">Subscribe</button>
  <div class="signup-form" style="display:none;">
    Content
  </div>
</div>

jQuery:

(function($) {

  $(".signup-button").on('click', function() {
    $(".signup-button").not(this).find(".signup-form").hide();
    $(this).find(".signup-form").toggle("slow");
  });

})(jQuery);

JSFiddle: https://jsfiddle.net/v6bmphct/3/

Ad

Answer

One option would be to attach the event listener directly to the descendant button element. In doing so, the click event isn't triggered when clicking on the other content. You would also have to change instances of $(this) to $(this).parent() or $(this).closest('.signup-button').

Updated Example

$(".signup-button .btn").on('click', function(e) {
  $(this).parent().find(".signup-form").toggle("slow");
  $(".signup-button").not($(this).parent()).find(".signup-form").hide();
});

Alternatively, since event.target is a reference to the clicked element, you could also just check to see if event.target is the button element by using the .is() method:

Updated Example

$(".signup-button").on('click', function(e) {
  if ($(e.target).is('.btn')) {
    $(this).find(".signup-form").toggle("slow");
    $(".signup-button").not(this).find(".signup-form").hide();
  }
});
Ad
source: stackoverflow.com
Ad