0

I have this code:

Full Code: https://codepen.io/anon/pen/wmLBxW

JavaScript code:

function HideOnClickOutside(aContentElement, aFullScreenElement) {
  const outsideClickListener = event => {
    event.preventDefault();
    let isClickInside = aContentElement.contains(event.target);
    if (!isClickInside) {
      aFullScreenElement.classList.toggle("hidden", true);
      removeClickListener();
    }
  };

  const removeClickListener = () => {
    document.removeEventListener("click", outsideClickListener);
  };

  document.addEventListener("click", outsideClickListener);
}

CSS

  #fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: auto;
  background: black;
  opacity: 0.5;
}

.hidden {
  display: none;
}

#journal-show-entry {
  display: flex;
  justify-content: center;
  width: 40%;
  height: 60%;
  border: 1px solid #9b6400;
  background-color: #ffffff;
}

HTML

<a href="#" onclick="ShowFullScreenDiv()">Link</a>

<div id="fullscreen" class="hidden">
  <div id="journal-show-entry">
  </div>
</div>

Which I found in this thread: How do I detect a click outside an element?

However just like in my CodePen, it triggers the outsideClickListener on the same click that adds the EventListener making the div hide itself again on the same click and therefore never shows.

Why is this happening?

indiehjaerta
  • 319
  • 1
  • 8
  • 19
  • Not sure what you want to happen when you click on the link? – Ziv Weissman Apr 14 '18 at 16:03
  • I want to show the fullscreen div with its children. And when I click outside the div with the content when fullscreen is shown I want it to hide itself. – indiehjaerta Apr 14 '18 at 16:16
  • Added a solution but please add the JS file and HTML to the post because external links cannot be trusted to live more than this post. – Ziv Weissman Apr 14 '18 at 16:56

1 Answers1

1

What is happening is that the event is propagating onto the next layer (the hidden div)

Adding this will fix your problem:

function ShowFullScreenDiv(event) {
  event.stopPropagation(); // <-- add this
  divFullScreen.classList.toggle("hidden", false);
  HideOnClickOutside(divEntry, divFullScreen);
}

And ofcourse add the event to the html:

<a href="#" onclick="ShowFullScreenDiv(event)">Link</a>
Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61