Quantcast
Channel: Server Side Up
Viewing all articles
Browse latest Browse all 11

Detect if Click is Inside an Element with JavaScript

$
0
0

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">

	</div>
</div>

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( event.target ) ){
		// 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.

Conclusion

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!

The post Detect if Click is Inside an Element with JavaScript appeared first on Server Side Up.


Viewing all articles
Browse latest Browse all 11

Trending Articles