0

How to detect click outside two blocks

My jquery code is:

$(document).ready(function() {
    $('.js-bottom-navbar__consultant').click(function () { 
        $('.bottom-navbar__consultant-content').toggleClass('navbar__consultant-content--opened');
    });

this part detects click even on child elements, wo it doesn't work

    $(document).on('click', function(e) {
        if ($(e.target).is('.js-bottom-navbar__consultant') === false) {
            $('.bottom-navbar__consultant-content').removeClass('navbar__consultant-content--opened');
        }
    }); 
});

html

<div class="js-bottom-navbar__consultant bottom-navbar__consultant">
  <p>Some text too</p>
  <p class="js-consultant__button consultant__button consultant__button--online">                <span class="button__text--desktop">Some text</span>
  </p>
</div>
<div class="bottom-navbar__consultant-content navbar__consultant-content ">
  <div class="consultant__details consultant__status--online consultant__status">
    <img class="consultant__img" src="">
    <div class="consultant__text">
      <p class="consultant__name">
        Name
      </p>
      <p class="consultant__specification">
        Specification
      </p>
      <a href="#" class="consultant__question">
        Start
      </a>
    </div>
  </div>       
</div>

Jsfiddle

Angelzzz
  • 1,356
  • 2
  • 10
  • 20
  • Include the relevant HTML please. As is, your question/snippet references elements and "blocks" that we know nothing about. – Tyler Roper Mar 15 '17 at 15:07
  • I added jsfiddle, stack doesn't allow to post question with a lot of code http://jsfiddle.net/g8f9Lzcw/1/ – Angelzzz Mar 15 '17 at 15:11
  • First off, your HTML is not that long. But more importantly, Stack allows the shortest amount of code necessary - If the shortest amount necessary is 100 lines, then so be it. There is nothing that says "Stack doesn't allow a lot of code". – Tyler Roper Mar 15 '17 at 15:13

1 Answers1

0

I've done a good deal of work on exploring clicking outside of elements. There's also a fairly lengthy answer-thread that goes through some of the methods. My solution to your specific question of finding both elements would be something like this:

document.body.addEventListener('click', function(e){
    if(!element1.contains(e.target) && !element2.contains(e.target)){
         //do the work here
    }
});

Where element1 and element2 are the elements you want to check the click was outside of.

Community
  • 1
  • 1
Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40