D
D
Dmitry2021-07-09 11:35:27
JavaScript
Dmitry, 2021-07-09 11:35:27

Why is the block removed on click?

Faced such a problem. When you click on the button, a block appears, but after some time it disappears for some reason, I can’t understand why. Example below

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="container">
  <div class="header__list--item menu-click">Материалы</div>
  <div class="header__menu">
    Контетн
  </div>
</div>

.header__list--item {
  padding: 18px 32px;
  background: blue;
  color: #fff;
  text-align: center;
  cursor: pointer;
}

.header__menu {
  display: none;
  background: red;
  padding: 52px 18px;
  text-align: center;
  color: #fff;
}

$(function() {
    var res = $(".header__menu");
    $(".menu-click").on("click", funk);
    $(document).click(function(e) {
        if (!$(e.target).parents().hasClass('menu-click')) funk(false);
    });

    $('.header__menu').on('click', function(e) { e.stopPropagation() });

    function funk(flag) {
        if (res.css("display") == "none" && flag) {
            res.fadeIn(300);
        } else {
            res.fadeOut(300);
        }
    }
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FeST1Val, 2021-07-09
@moiseev1788

because it works

$(document).click(function(e) {
        if (!$(e.target).parents().hasClass('menu-click')) funk(false);
    });

You can essentially remove .parents, then it will not be activated on a click on the menu-click itself, and next time it's better to make a sandbox than just code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question