I have an alert div, which appears when a user clicks on a link. Now what I want to do is to hide that div when somebody clicks outside it. It by default has a fadeoff event attached, but I want the user be able to hide that div by clicking elsewhere.
I tried putting $('body').click inside the function call but its does not work. Please help, here is my JavaScript:
var messageDiv = $('<div id="cannotDoDiv"></div>');
$('body').append(messageDiv);
function appendDiv(this_element,msg)
{
var pos = this_element.offset();
var width = this_element.width();
messageDiv.css({
left: (pos.left - 20) + 'px',
top: pos.top + 30 + 'px'
});
$('#cannotDoDiv').fadeOut();
$('#cannotDoDiv').html(msg).show().delay(1000).fadeOut();
$('body').click(function(){
$('#cannotDoDiv').hide();
});
}
$("span#selfLike").click(function(){
appendDiv($(this),'You cannot like your own post!');
});
When I remove:
$('body').click(function(){
$('#cannotDoDiv').hide();
});
from my function $("span#selfLike").click works fine, otherwise it is not being fired.
Edit: I think, I understood what you are trying.. see updated code below which
.oneto bind only once and unbinds after it is done..Used on
fadeIncallback so it will be binded only after the div is visible..Below is the complete code.. Updated DEMO here
Note: This also closes when you click on the
$('#cannotDoDiv')div. Add an click listener and stopPropogation if you don’t want that to happen.Try$(document).click(function(){instead of body.