Categories
JavaScript Answers jQuery

How to Trigger an Event When Clicking Outside an Element with jQuery?

Spread the love

Sometimes, we want to trigger an event when clicking outside the element with jQuery.

In this article, we’ll look at how to trigger an event when clicking outside the element with jQuery.

Trigger Event When Clicking Outside an Element with jQuery

To trigger an event when clicking outside the element with jQuery, we can listen to the click event on the html element.

Then in the event handler, we can check which element is clicked.

For instance, we write:

<div id='your-div-id'>
  hello world
</div>

to add a div and we want to detect whether we clicked outside of it.

Then we write:

$('html').click((e) => {
  if (e.target.id !== 'your-div-id' && $(e.target).parents('#your-div-id').length === 0) {
    console.log('clicked outside')
  }
});

to select the html element with $('html').

Then we call click on it with the click event listener.

We get the element we clicked on with the e.target property.

So if its id isn’t 'your-div-id' and its parent elements also don’t contain the div with ID your-div-id as returned by the parents method, then we know we clicked outside the div with ID your-div-id.

Therefore, when we click outside the div we added, we see 'clicked outside' logged in the console.

Conclusion

To trigger an event when clicking outside the element with jQuery, we can listen to the click event on the html element.

Then in the event handler, we can check which element is clicked.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *