Amir
Amir

Reputation: 537

Remove class when user clicks wherever on the page

I have 2 button which will toggle/remove class when user clicks on it.

$('.social-toggle').on('click', function() {
  $('.social-networks').not($(this).next()).removeClass('open-menu')
  $(this).next().toggleClass('open-menu');
});

Clicking on another share button will open another box at the same time the first is closed. But want Clicking anywhere outside the box close them. Do yo know how can i do that? Also here is my HTML

<div class="share-button">
  <a href="#" class="social-toggle">Share</a>
<div class="social-networks">
  <ul>
    <li class="social-twitter">
      <a href="http://www.twitter.com">T</a>
    </li>
    <li class="social-facebook">
    <a href="http://www.facebook.com">F</a>
    </li>
    <li class="social-gplus">
    <a href="http://www.gplus.com">G+</a>
    </li>
  </ul>
</div>
   </div>

JSFIDDLE

Upvotes: 1

Views: 1834

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You could register a click handler for the document, then check whether the target was a .social-toggle(to prevent double processing - another option is to stop the propagation of click from .social-toggle handler.) element if not close the opened .social-networks element.

$(document).click(function (e) {
    if (!$(e.target).hasClass('social-toggle')) {
        $('.social-networks.open-menu').removeClass('open-menu')
    }
})

Demo: Fiddle


Using propagation(not a fan of this approach because if you need similar functionality in another part of the page that will be broken if you stop the propogation)

$('.social-toggle').on('click', function (e) {
    e.stopPropagation();
    $('.social-networks').not($(this).next()).removeClass('open-menu')
    $(this).next().toggleClass('open-menu');
});

$(document).click(function (e) {
    $('.social-networks.open-menu').removeClass('open-menu')
})

Demo: Fiddle

Upvotes: 1

Related Questions