How to detect a click outside an element with jQuery
In this tutorial, we are going to see how to detect a click outside an element with jQuery. In jQuery, if you want to know when a click occurs outside of an element, you have to use the .stopPropagation() method.
The .stopPropagation() method prevents events from propagating to parent elements. This means “If we click on a child element, the click should not happen for the parent element.”
jQuery Code:
jQuery(function($){ $('#mydiv').click(function(e){ alert('clicked inside'); e.stopPropagation(); // Prevent bubbling }); $(document).click(function() { alert('clicked outside'); }); });
CSS Code:
div { padding: 25px; margin: 10px; border: 2px solid red; float: left; }
HTML Code:
<!DOCTYPE html> <html> <head> <title>Detect a click outside an element with jQuery</title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> // Put the jQuery code Her. </script> <style type="text/css"> /* Put the CSS Style Here */ </style> </head> <body> <div id='mydiv'>Lorem ipsum</div> </body> </html>
Result |
---|
Lorem ipsum
|