How to listen to Clicks outside a DOM element using jQuery

It is sad to know the fact that DOM events or the so called JavaScript Events do not allow you to find out any clicks outside the element. One method in which you can detect clicks outside the DOM element is to listen to the clicks on the whole webpage and after that see if your targeted DOM element was present or not.

Without the use of jQuery, it actually becomes very difficult to find out the DOM element that was clicked on different browsers and yet after this also you will need to have explanation in case your control is having several layers and if either of the DOM elements has been clicked.

So to avoid all these complexities we have a much easier and simpler approach. You should first listen to all the clicks on the entire webpage  with the use of <html> tag instead of using <body> tag since the body tag will not spread throughout the webpage in case the content on your webpage is short. Once you are done with this you must listen to all the clicks on your control and put an end to the event so that it does not bubble up to the HTML handler.

Here is a piece of code that will help you easily detect a click outside an element by attaching a CLICK event to the document body that will close the window and a separate CLICK event to the window that will stop the propagation to the document body :

$('html').click (function ()
{
// Execute the piece of  code, such as closing a custom control or hiding a menu
});

$('#custom_control').click (function (event)
{
event.stopPropagation ();
});

Recently Published

»

Is Your Business Site Fully Accessible?

Does your business site have full accessibility? Even with the ADA ...

»

Secure Web: 5 Best Practices For Application Development

There are several essential best practices for secure web ...

»

Laravel PHP Framework: Features and benefits for web development

Companies and organizations are focusing on developing custom web ...

»

Web Development Vs. Software Development: What Is the Difference?

As technology continues to transform all aspects of our lives, a lot ...

»

Web Redesign : Is Your Landing Page Begging for one?

How do you know when it’s time to web redesign your landing page? ...

»

Customer Acquisition: Few Steps To Improve This.

Customer acquisition is essential to any business’s success — to ...

»

Mobile App Development Tools: 5 Enterprise-Ready For Rapid Deployment

There are several enterprise-ready mobile app development tools for ...

»

Docker: How To Build Better Development Security With It

The top concern among developers and DevOps teams is security within ...

»

Mobile Development: How to Reduce Costs

Modern markets have become so competitive that it has become vital ...