Search code examples
javascriptjqueryipadtablet

How to open a box on screen by clicking a link and hide it when clicked outside in JS


My goal is to have #box2 appear when I click on #box1 but when you click on something other than #box2, it will display none and only #box1 will show.

Here are my 2 boxes, they are just 2 styled divs:

 var condition;


 $(document).click(function() {

   if (condition === 'block') {
     $(":not(#box2)").click(function() {
       $("#box2").hide();
     });
   }

 })



 $('#box1').click(function(e) {
   $('#box2').css('display', 'block');
   condition = 'block';
 });

 $('#box2').click(function(e) {
   $('#box2').css('display', 'none');
   condition = 'none';
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box1" style="width: 300px; height: 300px; background-color: red; margin-left: 100px; margin-bottom: 50px; position: absolute;">
</div>



<div id="box2" style="width: 300px; height: 300px; background-color: blue; margin-left: 150px; display: none; position: absolute;">
</div>

This current code works correctly the first time but after that, it wont run again. I am just wondering if there is a reset function or where I am going wrong?

Really what I want to do is make this work on an ipad so when the user clicks/taps away from the box, it will close. If there are better ways to do this on the Ipad tablet, please let me know!!

Any ideas?


Solution

  • Don't overcomplicate things. This is all the javascript you need, get rid of everything else:

    $(document).click(function () {
        $('#box2').hide();
    });
    
    $('#box1').click(function (e) {
        e.stopPropagation();
        $('#box2').show();
    });