Detect if Click is Inside an Element with JavaScript

Dan Pastori avatar
Dan Pastori October 11th, 2022

So this is a little script that I’ve included in some UI elements to check if a click takes place within the scope of the element. Why would you need this? Say you have a little drop down, autocomplete, etc. that should close when a click occurs outside of the element. You need to see if the user clicks within your autocomplete or outside of it.

For example, I’ll usually have a container that looks like this:

<div id="container">
	<input type="text" id="query"/>

	<div id="autocomplete">


What we want to do is check to see if a click is inside the element with id of container. If it is, we don’t want to close the autocomplete. If a click is outside of the container, we want to hide the autocomplete.

Let’s add the following JavaScript code:

let containingElement = document.querySelector('#container');

document.body.addEventListener('click', function( event ){
	if( containingElement.contains( ) ){
		// do nothing, click was inside container
	} else {
		// hide autocomplete, click was outside container.

What this does is grabs our containing element first. Then we add an event listener to the body of our page. We then check on every click if the containing element contains the click. We do that by adding the .contains() method to our element and passing the target element from the event. The .contains() method simply returns true or false if the the parameter element is within element we are checking. From there, we can handle the event accordingly.

While this is a pretty rudimentary example, there are multiple other areas where the JavaScript .contains() method comes in handy to make powerful UIs. Especially when it comes to scoped events and target elements.


Pretty quick tutorial, but has a variety of use cases. If you have any questions, reach out on Twitter (@danpastori). Would love to get your feedback!

Make sure to sign up for our mailing list if you want these tips & tutorials directly in your inbox!

Support future content

The Ultimate Guide to Building APIs and Single-Page Applications with Laravel + VueJS + Capacitor book cover.

Psst... any earnings that we make off of our book is being reinvested to bringing you more content. If you like what you read, consider getting our book or get sweet perks by becoming a sponsor.

Written By Dan

Dan Pastori avatar Dan Pastori

Builder, creator, and maker. Dan Pastori is a Laravel certified developer with over 10 years experience in full stack development. When you aren't finding Dan exploring new techniques in programming, catch him at the beach or hiking in the National Parks.

Like this? Subscribe

We're privacy advocates. We will never spam you and we only want to send you emails that you actually want to receive. One-click unsubscribes are instantly honored.