Learn12 Learn12 - 1 year ago 59
Javascript Question

Javascript click function fires only once then does not work

My goal is to have

appear when I click on
but when you click on something other than
, it will hide
and only
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 () {

$('#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 Source

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

$(document).click(function () {

$('#box1').click(function (e) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download