How to hide/collapse div when click on outside by using pure javascript -
i have made simple javascript function show , hide unable trigger outside click hide function.
html
<a href="javascript:void(0);" onclick="showhide()" class="btn" >click </a> <div id="myid"> <p>hello world</p> </div> css
.btn{ color:red; border-radius:5px; padding:10px; display:inline-block; } #test{ display:none; border:1px solid blue; width:200px; height:200px; margin:10px } javascript
function showhide(){ var div = document.getelementbyid("test"); if (div.style.display !== "none") { div.style.display = "none"; } else { div.style.display = "block"; } } please check code here.
no jquery please. thanks
you can naively handling global click events, , maintaining state.
in example below, clicks within element never reach document, outside via propagation. clicking button toggles display. keep in mind, clicking on element, or propagating element, stops propagation of click event document cause not respond properly.
var toggle = (function () { var visible = false, ele = document.getelementbyid('test'), btn = document.queryselector('.btn'); function flip () { var display = ele.style.display; ele.style.display = (display === 'block' ? 'none' : 'block'); visible = !visible; } btn.addeventlistener('click', flip); ele.addeventlistener('click', function (e) { e.stoppropagation(); }); document.addeventlistener('click', function (e) { if (visible && e.target !== btn) flip(); }); ele.style.display = 'none'; return flip; }()); body { font-family: sans-serif; } .btn { width: 180px; } #test { margin: 10px 0; padding: 20px; display: none; box-sizing: border-box; width: 180px; height: 180px; background-color: #eee; border: 2px solid #333; line-height: 96px; text-align: center; color: #333; } <button class="btn">click!</button> <div id="test"> <p>hello world!</p> </div> documentation:
Comments
Post a Comment