G
G
Gorila Lopster2020-04-22 12:53:41
css
Gorila Lopster, 2020-04-22 12:53:41

Targeting, clicking in a non-block area?

Hello please advise. How to remove the class (close the list) when clicking not in this block, but in the page area?

let dropListBtn = document.querySelector('.header__drop-arrow'),
    dropList = document.querySelector('.header__drop-list');

  /***header phone drop list */
  let openDropList = function () {
    dropListBtn.classList.toggle('active');
    dropList.classList.toggle('active');
  };
  dropListBtn.addEventListener('click', openDropList);

  window.onclick = function (event) {
    if (event.target == dropListBtn) {
      dropListBtn.classList.remove('active');
      dropList.classList.remove('active');
    }
  };

Wrote window.onclick , does not work (
there was another option
let target = elem = event.target;
    while (target != this) {
      if (target == dropListBtn) {
        dropListBtn.classList.toggle('active');
        dropList.classList.toggle('active');
        return;
      }
      target = target.parentNode;

    };
    dropListBtn.classList.remove('active');
    dropList.classList.remove('active');

it works, but down the page there is another element that interacts with javascript (lazy loading script for YouTube videos) when I start the video, an error occurs in the console
Uncaught TypeError: Cannot read property 'parentNode' of null
at HTMLDocument.document.onclick (scripts.min.js:1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stepan Potienko, 2020-05-03
@CatProgrammer

Try to make a transparent block on the whole page with z-index: -2 or more, and when you click on it, hide the list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question