PiotrS PiotrS - 28 days ago 5
CSS Question

Detect click inside/outside div



.container
{
width:500px;
height:500px;
background-color:grey;
}
.box
{
width:150px;
height:30px;
background-color:white;
position:relative;
top:130px;
left:10px;
color:black;
}
.window
{
height:300px;
width:250px;
background-color:red;
position:absolute;
left:200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="box" contenteditable="true">
</div>
<div class="window">
</div>
</div>





Hello,

I have one question, is possible to detect focus and blur into div (
class="box"
). I would like to click in div
class="box"
(when div is active) and the red box (
class="window"
) fadeOut and then when click outside "box" "window" fadeIn ?

Thank you for your time :)

Answer

You could do that using jQuery focus and blur event handler, .box on focus it hides .window and on blur it shows .window.

$(document).ready(function(){
	$('.box').on('focus',function(){
  	$('.window').hide(200);
  });
  $('.box').on('blur',function(){
  	$('.window').show(200);
  });
});
.container
{
  width:500px;
  height:500px;
  background-color:grey;
  }
.box
{
  width:150px;
  height:30px;
  background-color:white;
  position:relative;
  top:130px;
  left:10px;
  color:black;
  }
.window
{
  height:300px;
  width:250px;
  background-color:red;
  position:absolute;
  left:200px;
  }
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="box" contenteditable="true">
  </div>
  <div class="window">
  </div>
</div>