3
<a href="javascript:void(0)" onclick = "document.getElementById('light3').style.display='block';document.getElementById('fade').style.display='block'"><button type="button" name="" value="" id="readmorelink3">+<span class="rmore">Read More</span></button></a>

I'm using the above DOM classic onClick to simply display divs as a simple pop-up. I have created a close button within the div but I would also like to have the open divs hide when the user clicks the body or anywhere that isn't the open div. I have tried absolutely everything --

My simple Overlay (1 of 3)

<!-- read more overlays 1 -->

<div id="light" class="white_content">

<a class="close" href="javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'" class="textright" style="color: #DDD !important; float:right;">CLOSE X</a>

<h4>[Hey+]</h4>
<h3>Demo</h3>
<h3>SUP</h3>
<span> 2.5 fl. oz.</span><br>
<br>
<p>
Cool content, about cool things.
</p>

</div>

<!-- // read more overlays 1-->

I tried this guy:

$(document).click(function() {
    $('#mydiv').fadeOut(300);
});

I've messed with this guy:

 if($('#mydiv').is(":not(:visible)") ){

// and visa versa if visible etc


Also have tried.

 // To prevent hide #menu when click on #main
    $('#mydiv').click(function (e) {
        e.stopPropagation();
});

 // Click outsite of #menu
    $('html').click(function () {
    $('#mydiv').hide();
});

Realizing I have should have done this with simple jQuery and not inline; but I don't want to redo everything so seeking DOM / JavaScript solution. Simply to close the open or display: block divs > when they are displayed, by in addition clicking outside of the element or on body tag.

EG: DIV OVERLAY IS DISPLAYED > CLICK OUTSIDE OF ELEMENT AND IT CLOSES. I ADDED ONCLICK CLOSE BUTTON TO THE BODY TAG, BUT IT KILLED POPUP ENTIRELY, ADDED A WRAPPER, NO CIGAR.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • I've +1'd this for your realization about inline but should also say that it's not just a best practice to avoid inline js there are serious security concerns – hammus Apr 25 '14 at 03:33

3 Answers3

3

See this answer: Close/hide an element when clicking outside of it (but not inside)

  • Assign the desired event listener (like "click") to document or window using EventTarget.addEventListener()
  • Use Event.target in combination with Element.closest() as negation ! - in order to check whether the Event.target (the element that initiated the Event) - its self or closest ancestor have a specific selector.
  • To control an element visibility create a CSS class that does the necessary styling, and use Element.classlist to add, remove or toggle that class (as needed).

Modal example:

// DOM utility functions:
const el = (sel, par) => (par ||document).querySelector(sel);
const els = (sel, par) => (par ||document).querySelectorAll(sel);


// Task: modal:
const toggleModal = (evt) => {
  const sel = evt.currentTarget.dataset.modal;
  if (!sel) evt.currentTarget.closest(".Modal").classList.remove("is-open");
  el(sel).classList.add("is-open")
};

els("[data-modal]").forEach(elModalButton => {
  elModalButton.addEventListener("click", toggleModal);
});

addEventListener("click", (evt) => {
  // if click on button or inside modal — do nothing
  if (evt.target.closest("[data-modal]") || evt.target.closest('.Modal')) return;
  // else — close any open modal:
  els(".Modal.is-open").forEach(elModalOpen => {
    elModalOpen.classList.remove("is-open");
  });
});
/* MODAL */

.Modal {
  position: fixed;
  z-index: 99999;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  min-width: 200px;
  padding: 2em;
  background: gold;
  
  /*Hide modal by default */
  pointer-events: none;
  visibility: hidden;
  opacity: 0;
  transition: 0.4s;
}

.Modal.is-open {
  background: red !important;
  pointer-events: auto;
  visibility: visible;
  opacity: 1;
}
<button data-modal="#modal_1" type="button">Call modal 1</button>
<button data-modal="#modal_2" type="button">Call modal 2</button>


<div class="Modal" id="modal_1">
  <h2>Modal 1 title</h2>
  <p>Pop 1 description...</p>
  <button type="button" data-modal>OK</button>
</div>

<div class="Modal" id="modal_2">
  <h2>Modal 2 title</h2>
  <p>Pop 2 description...</p>
  <button type="button" data-modal>OK</button>
</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • @leemo :) thanks so much! I'll make a coffee now and enjoy all this kindness ;) – Roko C. Buljan Apr 25 '14 at 04:35
  • you're welcome, you're answer gave me some ideas for a project I'm working on. I never think to go with full screen overlays but there are so many benefits. Cheers. – hammus Apr 25 '14 at 05:50
  • @leemo uhh... i've done an extensive research ans tests on http://jsbin.com/gokuf/5/ (5 and 0 to 8) and ended up with this approach I always used. None of the other suggestions I've seen on this popular problem http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element was complete and explained. Even the accepted answer is the worse possible solution. – Roko C. Buljan Apr 25 '14 at 07:08
1

A quick (maybe slightly computationally expensive) dirty hack would be something like:

$("body").click(function() {

    $(".white_content").each(function(){
        if($(this).css("display") !== "none")
        { 
            $(this).hide();
        }
    });
});

Working fiddle.

hammus
  • 2,602
  • 2
  • 19
  • 37
  • Yes; but it requires a rewrite of my code of onClick - so it's basically a different approach; thanks tho! – Dr Upvote Apr 26 '14 at 02:43
0

Try this:

  $("body").click(function (e) {
            var elt = $(e.target);
    if (!($(e.target).attr("id") == "light") && !($(e.target).parents("div").attr("id")=="light"))
            {
                $("#light").hide();
            }
        });

Its depends on your conditions. Anyways I have edited my post, you can check now.

Naveen Chandra Tiwari
  • 5,055
  • 3
  • 20
  • 26
  • 1
    This is a bad answer. http://jsbin.com/lehuz/2/edit :( – Roko C. Buljan Apr 25 '14 at 04:57
  • You meant something like this? http://jsbin.com/lehuz/3/edit which is still a bad example cause if you have a button inside a popup will trigger the close event. so.... – Roko C. Buljan Apr 25 '14 at 04:59
  • if you already use native `e.target` than why not use `e.target.id === "light"` ? Also if you don't set in CSS `body{height:100%}` your body will be as tall as the inner content. So it's not good. A user might click on `"html"` but your modal will not go away. – Roko C. Buljan Apr 25 '14 at 06:53