Detect click outside div using javascript
It depends on the individual use case but it sounds like in this example there are likely to be other nested elements inside the main div e.g. more divs, lists etc. Using Node.contains would be a useful way to check whether the target element is within the div that is being checked.
window.addEventListener('click', function(e){
if (document.getElementById('clickbox').contains(e.target)){
// Clicked in box
} else{
// Clicked outside the box
}
});
An example that has a nested list inside is here.
How to detect click outside an element with a class selector Using Pure Javascript (without using Jquery)
Made the following changes to the script
var popElement = document.getElementsByClassName("pop");
document.addEventListener('click', function(event) {
for(i=0; i < popElement.length; i++){
popEl = popElement[i];
var isClickInside = popEl.contains(event.target);
if (!isClickInside) {
alert("Outside");
} else {
alert("Inside");
break;
}
}
});
Javascript Detect click event outside of div
In pure Javascript
Check out this fiddle and see if that's what you're after!
document.getElementById('outer-container').onclick = function(e) {
if(e.target != document.getElementById('content-area')) {
document.getElementById('content-area').innerHTML = 'You clicked outside.';
} else {
document.getElementById('content-area').innerHTML = 'Display Contents';
}
}
http://jsfiddle.net/DUhP6/2/
Detect click outside React component
The following solution uses ES6 and follows best practices for binding as well as setting the ref through a method.
To see it in action:
- Hooks Implementation
- Class Implementation After React 16.3
- Class Implementation Before React 16.3
Hooks Implementation:
import React, { useRef, useEffect } from "react";
/**
* Hook that alerts clicks outside of the passed ref
*/
function useOutsideAlerter(ref) {
useEffect(() => {
/**
* Alert if clicked on outside of element
*/
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
/**
* Component that alerts if you click outside of it
*/
export default function OutsideAlerter(props) {
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef);
return <div ref={wrapperRef}>{props.children}</div>;
}
Class Implementation:
After 16.3
import React, { Component } from "react";
/**
* Component that alerts if you click outside of it
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.wrapperRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}
Before 16.3
import React, { Component } from "react";
/**
* Component that alerts if you click outside of it
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Set the wrapper ref
*/
setWrapperRef(node) {
this.wrapperRef = node;
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.setWrapperRef}>{this.props.children}</div>;
}
}
How do I detect a click outside an element?
Note: Using
stopPropagation
is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks article for more information. Consider using this method instead.
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
Detect clicks outside of specific div and all of it's children
You're on the right way and only need one little change inside your code.
Instead of only checking if the event.target is the same as the div, also check if the div contains the event target:
var container = document.getElementsByClassName('container')[0];
document.addEventListener('click', function( event ) {
if (container !== event.target && !container.contains(event.target)) {
console.log('clicking outside the div');
}
});
If for some reason HTMLnode.contains() is not supported (safari, im looking at you), you can use following snippet to check if an element contains another:
function childOf( node, ancestor ) {
var child = node;
while (child !== null) {
if (child === ancestor) return true;
child = child.parentNode;
}
return false;
}
Detect click outside element
Keep in attention that this solution only works with Vue 1.
Can be solved nicely by setting up a custom directive once:
Vue.directive('click-outside', {
bind () {
this.event = event => this.vm.$emit(this.expression, event)
this.el.addEventListener('click', this.stopProp)
document.body.addEventListener('click', this.event)
},
unbind() {
this.el.removeEventListener('click', this.stopProp)
document.body.removeEventListener('click', this.event)
},
stopProp(event) { event.stopPropagation() }
})
Usage:
<div v-click-outside="nameOfCustomEventToCall">
Some content
</div>
In the component:
events: {
nameOfCustomEventToCall: function (event) {
// do something - probably hide the dropdown menu / modal etc.
}
}
Working Demo on JSFiddle with additional info about caveats:
https://jsfiddle.net/Linusborg/yzm8t8jq/
How do I detect a click outside an element?
Note: Using
stopPropagation
is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks article for more information. Consider using this method instead.
Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
$(window).click(function() {
//Hide the menus if visible
});
$('#menucontainer').click(function(event){
event.stopPropagation();
});
Detect click inside/outside div
You could do that using jQuery focus
and blur
event handler, .box
on focus
it hides .window
and on blur
it shows .window
.
$(document).ready(function(){ $('.box').on('focus',function(){ $('.window').hide(200); }); $('.box').on('blur',function(){ $('.window').show(200); });});
.container{ width:500px; height:500px; background-color:grey; }.box{ width:150px; height:30px; background-color:white; position:relative; top:130px; left:10px; color:black; }.window{ height:300px; width:250px; background-color:red; position:absolute; left:200px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="container"> <div class="box" contenteditable="true"> </div> <div class="window"> </div></div>
Detect click inside/outside of element with single event handler
Using jQuery:
$(function() {
$("body").click(function(e) {
if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {
alert("Inside div");
} else {
alert("Outside div");
}
});
})
#myDiv {
background: #ff0000;
width: 25vw;
height: 25vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"></div>
Related Topics
Invert Text Color on Mouse Hover
How to Break Line in JavaScript
Cannot Access CSSrules from Local CSS File in Chrome 64
Responsive Horizontal Page Sliding
Need to Find Height of Hidden Div on Page (Set to Display:None)
Python Library for Rendering HTML and JavaScript
Angular2 Router 2.0.0 Not Reloading Components When Same Url Loaded with Different Parameters
How to Disable the Save Password Bubble in Chrome Using JavaScript
In Angularjs, Any Inline JavaScript Code That Included in HTML Templates Doesn't Work
JavaScript Beforeunload Detect Refresh Versus Close
How to Listen/Detect Changes to an Input Value - When the Input Value Is Changed via JavaScript
Is There Any "On Dom Change" Event
Html:Draw Table Using Innerhtml
How to Reach the Element Itself Inside Jquery's 'Val'
How to Programmatically Detect Size Limit for Data Url