user1493948
user1493948

Reputation:

Trying to close containers when a click events occurs outside the container

I have two icons which open their containers and they also close each others containers however, I have been unable to close the containers when a click occurs outside the containers.

Please have a look at this fiddle example

Here is the code

$('.btn-one').click(function() {
  if ($(this).attr('data-container-status') == 'is-open') {
    $(this).next().removeClass('abc-active');
    $(this).attr('data-container-status', 'is-closed');
  } else {
    closeAll();
    $(this).next().addClass('abc-active');
    $(this).attr('data-container-status', 'is-open');
  }
});

$('.btn-two').click(function() {
  if ($(this).attr('data-container-status') == 'is-open') {
    $(this).next().removeClass('abc-active');
    $(this).attr('data-container-status', 'is-closed');
  } else {
    closeAll();
    $(this).next().addClass('abc-active');
    $(this).attr('data-container-status', 'is-open');
  }
});

function closeAll() {
  $('.container').removeClass('abc-active');
  $('.abc-btn').attr('data-container-status', 'is-closed');
}

Upvotes: 1

Views: 228

Answers (2)

Gaurav
Gaurav

Reputation: 133

I have cloned & edited your fiddle. Basically added this click handler and some style changes.

https://jsfiddle.net/GauravKesarwani/q3eauk6b/48/

  var icon = $('.icon');
    var container = $('.container');

    $('.test').click(function (e) {
      var className = e.target.className;
      if (className.indexOf('icon') !== -1 || className.indexOf('container') !== -1) {
        return;
      }
      closeAll();
    });

Upvotes: 0

Bragadeeswaran
Bragadeeswaran

Reputation: 278

please update your script and the end as follows: $('div.test').focusout(function(){closeAll();});

Upvotes: 1

Related Questions