user1110562
user1110562

Reputation: 423

Hide an element when clicking anywhere outside it

I am trying to have an element be hidden when you click anywhere outside of it.

It is a drop down that appears when you click on the CART link in the top left. The problem I seem to be facing is two fold.

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV. I am guessing it's because I'm not targeting the correct classes in this piece of code:

$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid. Again this must relate to an error in my syntax / logic in the above piece of code.

Can someone please point me in the correct direction?

Thanks.

Upvotes: 0

Views: 898

Answers (2)

freginold
freginold

Reputation: 3956

If you change the way you're checking the classes and elements, it will work. See this fiddle for a working example, using the code below:

https://jsfiddle.net/freginold/kv44k1uu/

HTML:

<div>
  A div
</div>
<br>
<div id='cart' class='cart-dropdown'>
  Cart
</div>
<br>
<div>
 Another Div
</div>

CSS:

div {
  border: 1px solid blue;
  margin: 5px;
  display: inline-block;
}

JavaScript:

$(document).click (function (e) {
//alert($(e.target).hasClass("cart-dropdown"));
  if (!$(e.target).hasClass('cart-dropdown') && !$(e.target).hasClass('cart-nav-item') && !$(e.target).hasClass('cart-full')) {
    $('.cart-dropdown').hide();
  }
});

You were on the right track; you just had to target the element through jQuery like @Our_Benefactors said, and then change the way you checked the element's class.

Upvotes: 1

Our_Benefactors
Our_Benefactors

Reputation: 3539

You need to change

e.target 

to

$(e.target) 

to treat it as a jquery object.

Upvotes: 0

Related Questions