2

I want to hide an element if it is clicked outside the element it self. als But it can't be closed if the menu button is clicked.

Now I have the following code:

$(document).mouseup(function test (e) {
  var button = $('.menu-button').data('clicked', true);
  var container = $(".sf-menu");
    if (!container.is(e.target) && container.has(e.target).length === 0 && button.data('clicked') == false) {
        container.hide();
    }
});

But the problem seems to be in:

button.data('clicked') == false)

How to write this code correctly?

Thnx!

Justin
  • 53
  • 7
  • try console logging button.data('clicked') and see if it is a string or a boolean - if you want to know what was clicked, look at e.target - also stop setting the clicked to true before testing if it is false – mplungjan Feb 04 '17 at 13:17
  • 2
    Hard to understand what you're trying to achieve, but what I see is that you set data clicked to true all the time, so can't be false – romuleald Feb 04 '17 at 13:18

2 Answers2

0

you need to use $(button).data('clicked') and not button.data('clicked') as button will contain the jquery object returned by $('.menu-button').data('clicked', true);

$(document).mouseup(function test (e) {
  var button = $('.menu-button').data('clicked', true);
  var container = $(".sf-menu");
    if (!container.is(e.target) && container.has(e.target).length === 0 && $(button).data('clicked') == false) {
        container.hide();
    }
});
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You should replace

var button = $('.menu-button').data('clicked', true);

with

var button = $('.menu-button').data('clicked', button.is(e.target));
Stash
  • 3
  • 2