Javascript Toggle : Hide Div On Click Of Anywhere
I have two divs. When I click on 3 dots , then the div is appearing and on clicking the same 3 dots , same div is disappearing. But I want to hide the div, even if I click anywhere
Solution 1:
Praveen's answer is nice but you can also achieve the same without tweaking your HTML.
Just add this to your jQuery:
$(window).click(function() {
//Hide the menus if visible
$('.discussion_edit_div').hide('fast');
});
$("#discussion_declined , #discussion_pending").click(function(e) {
e.stopPropagation();
var relatedDiv = $(this).closest('.panel').find('.discussion_edit_div');
relatedDiv.toggle("fast");
$('.discussion_edit_div').not(relatedDiv).hide('fast');
});
And your are good to go.
This achieves one more thing which is that once you have opened one ul, then you can directly toggle to another ul by clicking once. In Praveen's answer you have to click twice in order to open the other ul.
Check the link:https://jsfiddle.net/zfqqqr1c/1/
Solution 2:
How Bootstrap handles this is interesting. They have a mask, and the only thing you can click is the mask or the items in the menu.
$(function () {
$(".mask").hide();
$("nav > ul > li > a").click(function () {
$(this).closest("li").addClass("open");
$(".mask").show();
returnfalse;
});
$(".mask").click(function () {
$(this).hide();
$(".open").removeClass("open");
});
});
* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none; line-height: 1; box-sizing: border-box;}
body {background-color: #f5f5f5;}
a {text-decoration: none; color: inherit;}
.mask {position: fixed; top: 0; bottom: 0; right: 0; left: 0; z-index: 8;}
nav > ul > li {display: inline-block; position: relative; width: 30%;}
nav > ul > lia {display: block; padding: 5px; border: 1px solid #ccc;}
nav > ulul {position: absolute; left: 0; right: 0; z-index: 9; display: none;}
nav > ul > li.open > ul {display: block;}
<scriptsrc="https://code.jquery.com/jquery-2.2.4.js"></script><divclass="mask"></div><nav><ul><li><ahref="">Main Item 1</a><ul><li><ahref="">Sub Item 1</a></li><li><ahref="">Sub Item 2</a></li><li><ahref="">Sub Item 3</a></li><li><ahref="">Sub Item 4</a></li><li><ahref="">Sub Item 5</a></li></ul></li><li><ahref="">Main Item 2</a><ul><li><ahref="">Sub Item 1</a></li><li><ahref="">Sub Item 2</a></li><li><ahref="">Sub Item 3</a></li><li><ahref="">Sub Item 4</a></li><li><ahref="">Sub Item 5</a></li></ul></li><li><ahref="">Main Item 3</a><ul><li><ahref="">Sub Item 1</a></li><li><ahref="">Sub Item 2</a></li><li><ahref="">Sub Item 3</a></li><li><ahref="">Sub Item 4</a></li><li><ahref="">Sub Item 5</a></li></ul></li></ul></nav>
Post a Comment for "Javascript Toggle : Hide Div On Click Of Anywhere"