Click outside the div
$('body').click(function(e){
if( e.target.id == 'bbb' )
{ return true; }
else
{ $('#bbb').hide(); }
});
Note: There are several ways to do this, in any case, we need to listen for a click on the parent element, weather is a direct parent, such as #aaaor a distant parent, such as bodyor document. In this way, we can capture clicks that occur outside #bbb.
Now that we have it, we need it .hideNOT to happen if the user clicks a button #bbb. We can do this in two ways.
,
#bbb. click 'bubble' . , click ,#bbb. , , , , , . , , , .#bbb. , . , , ,#bbb.#bbb.hide, true, ,click, . , , -, .
, , , #bbb, . , .
http://jsfiddle.net/tpBq4/// @Raminson, .
, , jQuery.
var isOutSide = true
bbb = documment.getElementById('bbb');
document.body.addEventListener('click', function(){
if(!isOutSide){
bbb.style.display = 'none';
}
isOutSide = true;
});
bbb.addEventListener('click', function(){
isOutSide = false;
});
click, document. document, . click , document:
$(function () {
$(document).on('click', function () {
$('#bbb').hide();
});
$('#bbb').on('click', function (event) {
event.stopPropagation();
});
});
event.stopPropagation(): http://api.jquery.com/event.stopPropagation/
, . this, , this document.
https://github.com/tylercrompton/clickOut
:
$('#bbb').clickOut(function () {
$(this).hide();
});
OK
* jquery. IE
, JQuery $()
function $g(element) {
return document.getElementById(element);
}
function globalClickEventListener(obj){
this.fire = function(event){
obj.onOutSideClick(event);
}
}
,
.
function initialize(){
// $g('body') will return reference to our document body. parameter 'body' is the id of our document body
$g('body').globalClickEventListeners = new Array();
$g('body').addGlobalClickEventListener = function (listener)
{
$g('body').globalClickEventListeners.push(listener);
}
// capture onclick event on document body and inform all listeners
$g('body').onclick = function(event) {
for(var i =0;i < $g('body').globalClickEventListeners.length; i++){
$g('body').globalClickEventListeners[i].fire(event);
}
}
}
, clcik
function goListening(){
var icanSeeEveryClick = $g('myid');
var lsnr = new globalClickEventListener(icanSeeEveryClick);
// add our listener to listeners array
$g('body').addGlobalClickEventListener(lsnr);
// add event handling method to div
icanSeeEveryClick.onOutSideClick = function (event){
alert('Element with id : ' + event.target.id + ' has been clicked');
}
}
*
* , .