Detect click outside div using javascript

Javascript

Javascript Problem Overview


I'd like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, it should be considered a click inside, the same way if an element from outside the div is clicked, it should be considered an outside click.

I've been researching a lot but all I could find were examples in jquery and I need pure javascript.

Any suggestion will be appreciated.

Javascript Solutions


Solution 1 - 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.

Solution 2 - Javascript

You can check if the clicked Element is the div you want to check or not:

document.getElementById('outer-container').onclick = function(e) {
  if(e.target != document.getElementById('content-area')) {
      console.log('You clicked outside');
  } else {
      console.log('You clicked inside');
  }
}

Referring to Here.

Solution 3 - Javascript

you can apply if check for that inside your click event

if(event.target.parentElement.id == 'yourID')

Solution 4 - Javascript

I came up with a hack for this that's working well for me and that might help others.

When I pop up my dialog DIV, I simultaneously display another transparent DIV just behind it, covering the whole screen.

This invisible background DIV closes the dialog DIV onClick.

This is pretty straightforward, so I'm not going to bother with the code here. LMK in the comments if you want to see it and I'll add it in.

HTH!

Solution 5 - Javascript

In Angular 6 and IONIC 3, I do same as here:

import {Component} from 'angular/core';

@Component({
  selector: 'my-app',
  template: `
	<ion-content padding (click)="onClick($event)">
	  <div id="warning-container">
	  </div>
	</ion-content>
  `
})
export class AppComponent {
  onClick(event) {
    var target = event.target || event.srcElement || event.currentTarget;
    if (document.getElementById('warning-container').contains(target)){
      // Clicked in box
    } else{
      // Clicked outside the box
    }
  }
}

This working fine on web/android/ios. It might be helpful for someone, Thanks.

Solution 6 - Javascript

Try this solution it uses pure javascript and it solves your problem. I added css just for better overview... but it is not needed.

document.getElementById('outer-div').addEventListener('click', function(){
  alert('clicked outer div...');
});

document.getElementById('inner-div').addEventListener('click', function(e){
  e.stopPropagation()
  alert('clicked inner div...');
});

#outer-div{
  width: 200px;
  height: 200px;
  position: relative;
  background: black;
}

#inner-div{
  top: 50px;
  left: 50px;
  width: 100px;
  height: 100px;
  position: absolute;
  background: red;
}

<div id="outer-div">
  <div id="inner-div">
  </div>
</div>

Solution 7 - Javascript

I recently needed a simple vanilla JS solution which solves for:

  • Ignoring specific selectors including whether a parent contains one of these selectors
  • Ignoring specific DOM nodes

This solution has worked quite well in my app.

const isClickedOutsideElement = ({ clickEvent, elToCheckOutside, ignoreElems = [], ignoreSelectors = [] }) => {
	const clickedEl = clickEvent.srcElement;
	const didClickOnIgnoredEl = ignoreElems.filter(el => el).some(element => element.contains(clickedEl) || element.isEqualNode(clickedEl));
	const didClickOnIgnoredSelector = ignoreSelectors.length ? ignoreSelectors.map(selector => clickedEl.closest(selector)).reduce((curr, accumulator) => curr && accumulator, true) : false;

	if (
	  isDOMElement(elToCheckOutside) &&
	  !elToCheckOutside.contains(clickedEl) &&
	  !didClickOnIgnoredEl &&
      !didClickOnIgnoredSelector
	){
	  return true;
	}

	return false;
}

  const isDOMElement = (element) => {
    return element instanceof Element || element instanceof HTMLDocument;  
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser4697579View Question on Stackoverflow
Solution 1 - JavascriptJames BubbView Answer on Stackoverflow
Solution 2 - Javascriptmohamed-ibrahimView Answer on Stackoverflow
Solution 3 - Javascriptusman khanView Answer on Stackoverflow
Solution 4 - JavascriptnbardachView Answer on Stackoverflow
Solution 5 - JavascriptKamlesh KumarView Answer on Stackoverflow
Solution 6 - JavascriptthadamView Answer on Stackoverflow
Solution 7 - Javascriptdipole_momentView Answer on Stackoverflow