Learn12 Learn12 - 1 year ago 55
Javascript Question

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

My goal is to have

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


$('#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 id="box2" style="width: 300px; height: 300px; background-color: blue; margin-left: 150px; display: none; position: absolute;">

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?

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