
Skip to main content
Hide div on click outside of element in javascript/jQuery
Sometimes we need to hide the div on click outside of element in javascript/jquery. In jQuery or javascript, you can bind a click event on the document and hide that specific div on the click outside of it.
-
On click outside of element hide element using mouseup() method
<div id="targetElement"> <a class="agree" href="javascript:;">I Agree</a> <a class="disagree" href="javascript:;">Disagree</a> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).mouseup(function(e) { var container = $("#targetElement"); // if the target of the click isn't the container nor a descendant of the container if (!container.is(e.target) && container.has(e.target).length === 0) { container.hide(); } }); </script>
This code snippet will help you to hide the target element on click outside of the element. You can change the target element as per your requirement and can use it in your project.
-
On click outside of element hide element using click method on document
<div id="targetElement"> <a class="agree" href="javascript:void(0);">I Agree</a> <a class="disagree" href="javascript:void(0);">Disagree</a> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).click(function() { $("#targetElement").empty().hide(); }); </script>
This method will hide the target element on click outside of element and on click of the inner element itself.
Bootstrap
Cmd
CodeIgniter
Css
Drupal
Git
Html
Javascript
Jquery
Laravel
Nodejs
Php
Python
Sql
Typescript
Wordpress
Random Code Snippet Queries: Javascript
- How to validate empty space in textbox in Javascript
- How to check caps lock is on in javascript
- Get multiplication in javascript using array input
- Javascript set timeout function with example code
- Uncaught TypeError: Cannot read property 'addEventListener' of undefined
- Short-circuits conditionals
- Javascript get data-id attribute value
- JavaScript test() Method
- Javascript get only 10 characters from string
- Javascript to print Fibonacci series upto 15 Observations
- How to get the length of a number in JavaScript
- Generate 6 digit random number in javascript
- Cropper js with multiple images
- How to get data from localstorage in javascript
- How to set href value of anchor tag in javascript
- How to crop multiple images with cropper js
- How to open modal after redirect
- Uncaught TypeError: $(...).summernote is not a function
- Prism js horizontally overflowing its container
- How to validate input type file size in javascript
- How to Set data to localstorage in javascript
- Animating numbers counting Javascript
- How to fixed bootstrap navbar at top on scroll
- How to get query string value in javascript
- Json stringify