Close/hide an element when clicking outside of it (but not inside)
Asked Answered
T

3

4

I have a <div> that exists on a page and I need to make it so that when the user clicks outside of that element it will become hidden, but if the user clicks somewhere within the element, then it should stay.

I tried using
e.stopPropagation();
and
e.preventDefault();

adding it to the click event of that certain DIV but that didn't work.

Thanks!

Trieste answered 26/5, 2011 at 14:31 Comment(0)
F
4
  • 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).

const elPopup = document.querySelector("#popup");

addEventListener("click", (evt) => {
  if (!evt.target.closest("#popup")) elPopup.classList.remove("isOpen");
});
#popup {
  padding: 2rem;
  background: gold;
  display: none; /* Hidden popup by default */
}

#popup.isOpen {
  display: block;
}
<div id="popup" class="isOpen">
  Click outside to close me.<br>
  Click inside will do nothing.
</div>
  • Never use Event.stopPropagation() unless you really, really know what you're doing. Your app or third-party code should be always notified about all events happening in their context.

Usage example: Close popup modal on click outside

Frodine answered 26/5, 2011 at 19:46 Comment(7)
thank you. but it didnt work for me, maybe cuz i am using iframe? and the div i want to hide i add it on a event click? does that make sense?Trieste
Well, have you tried to just change to: ).live('click',function(ev)Frodine
Can you please write for me the full way of using ).live()? my problem is also cuz that div that i need to hide only appears after a click on something else, so its confusing.. any ideas?Trieste
Thank you, when i do the above code you wrote it now doesnt allow me to click on the select box that opens the div that after it is open i need to close it if user click any where out side that div. (all in iframe)Trieste
@Trieste JSFiddle was busy... so I made a JSBIN: look above!Frodine
@roXon, I used your code and it was great, but now in the div that needs to be closed i have a few more elements, that also when you click on them it shouldn't close, but it crazy to do allot of 'if' , is there a way using 'ev.target.id;' or something to get the parent element and then to see if that is the id i have? thank youTrieste
Between your other answers about this topic this is the easier to implementStagy
W
2

Probably the easiest way to do this will be to monitor clicks on the entire document, and ignore it if it's not that element. If it is, then hide it.

(function(div) {
    $(document).click(function(e) {
        if (e.srcElement !== div) $(div).hide();
    });
})($('div')[0]);

Edit: Derp, misunderstood, click inside should stay, otherwise hide... invert the equality check.

http://jsfiddle.net/robert/QcPx4/

Wedgwood answered 26/5, 2011 at 14:40 Comment(0)
N
0

useOuterClick

Hi . you can create custom hook like this:

export const useOuterClick = (elementRef, setElementVisibility) => {
useEffect(() => {
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
    function handleClick(e: any) {
        if (elementRef && elementRef.current) {
            const ref: any = elementRef.current;
            if (!ref.contains(e.target)) {
                setElementVisibility(false);
            }
        }
    }
}, [])};



 

then use it this way in your component:

import { useState, useRef } from 'react';
import useOuterClick from './hooks/useOuterClick';
 export const SampleComponent = () => {
const [activeElement, setActiveElement] = useState(false);
const elementRef = useRef();
useOuterClick(elementRef, setActiveElement);

return (
    <>
        <div ref={elementRef}>
            <button 
              onClick={() => setActiveElement(!activeElement)}>
               'this button can open and close div'
            </button>

            {activeElement &&
              <div>'this div will be hidden if you click on out side except 
                    button'
              </div>
             }
        </div>
    </>
);
};
Namara answered 5/9, 2022 at 23:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.