Hide Div When Clicked Outside It
The search result of the tutorial for the feature "hide div element when clicked outside the div" is mostly about using jQuery. However I want to keep my code pure without dependency (i.e., only vanilla JavaScript), so I tried to find a solution without using jQuey. Then I found [1], but it seems not working well for my code. As a result, I re-write the code and come up with a working code.
Please first see:
Source Code for Demo (html):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>Vanilla Javascript DropDown Menu Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="menu-dropdown">Menu ▼</div> <div id="menuDiv-dropdown" class="invisible"> content<br>content<br>content </div> <script src="vanilla-javascript-dropdown-menu-example.js"></script> </body> </html> |
Source Code for Demo (JavaScript):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | var dropdownMenuDiv = document.getElementById("menuDiv-dropdown"); var dropdownMenu = document.getElementById("menu-dropdown"); // hide popup div when clicking outside the div // http://www.webdeveloper.com/forum/showthread.php?t=98973 document.onclick = check; // Event accessing // http://www.quirksmode.org/js/events_access.html // Event properties // http://www.quirksmode.org/js/events_properties.html function check(e){ var target = (e && e.target) || (event && event.srcElement); if (!checkParent(target, dropdownMenuDiv)) { // click NOT on the menu if (checkParent(target, dropdownMenu)) { // click on the link if (dropdownMenuDiv.classList.contains("invisible")) { // Dynamically retrieve Html element (X,Y) position with JavaScript // http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element dropdownMenuDiv.style.left = dropdownMenu.getBoundingClientRect().left + 'px'; dropdownMenuDiv.classList.remove("invisible"); } else {dropdownMenuDiv.classList.add("invisible");} } else { // click both outside link and outside menu, hide menu dropdownMenuDiv.classList.add("invisible"); } } } function checkParent(t, elm) { while(t.parentNode) { if( t == elm ) {return true;} t = t.parentNode; } return false; } |
Source Code for Demo (CSS):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #menu-dropdown { font-size: 2em; color: blue; margin-left: 20px; } #menu-dropdown:hover { cursor: pointer; } #menuDiv-dropdown { font-size: 2em; padding: 10px; position: absolute; border: 1px solid blue; } .invisible { display: none; } |
References:
[1] | hide popup div when clicking outside the div |
[2] | Javascript Drop Down Menu |
[3] | [Golang] GopherJS DOM Example - Dropdown Menu |