jquery - hide elements when you click on the body html -


i have code, works fine, want make elements # content1, # content2 .. hidden when clicked on body. tried setting body z-index smaller div while did not help

    $(function() {            $('#div1').click(function() {              $('#content1, #content2, #content3').hide();              $('#content1').show();              /* other code ..*/            });              $('#div2').click(function() {              $('#content1, #content2, #content3').hide();              $('#content2').show();              /* other code ..*/            });      });
 html,body{width:100%;height:100%;}        #div1, #div2, #div3{             overflow:hidden;             float:left;             width:40px;             height:40px;             background:red;             margin:0 10px 0 0;           }           #content1, #content2, #content3{           overflow:hidden;           position:absolute;           top:50px;           background-color:#000;           color:#fff;           padding:2px 4px;      }
<!doctype html>  <html>  <body>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>          <div id="div1">            <div id="content1" style="display: none;">              text1            </div>          </div>          <div id="div2">            <div id="content2" style="display: none;">              text2            </div>          </div>          <div id="div3">            <div id="content3" style="display: none;">              text3            </div>          </div>  </body>  </html> 

try this:

$(function() {      var div1 = $("#div1");      var div2 = $("#div2");      var div3 = $("#div3");      $("body").on("click", function (e) {          if (div1.has(e.target).length || e.target == div1[0])              return;          else if (div2.has(e.target).length || e.target == div2[0])              return;          else if (div3.has(e.target).length || e.target == div3[0])              return;          $('#content1, #content2, #content3').hide();      });  });
html,body{width:100%;height:100%;}
<div id="div1">      <div id="content1">       text1      </div>  </div>  <div id="div2">      <div id="content2">       text2      </div>  </div>  <div id="div3">      <div id="content3">       text3      </div>  </div>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -