Learn12 Learn12 - 4 months ago 8
Javascript Question

Javascript click function fires only once then does not work

My goal is to have

#box2
appear when I click on
#box1
but when you click on something other than
#box2
, it will hide
#box2
and only
#box1
will show.

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

<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>


Here is my JS:

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';
});


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.

Answer

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();
});