I want to make a popup div that disappears when I click on it. I need pure js, not jQuery or anything else. So I do the following ...
which make the div to fade:
function closePopUps(){
if(document.getElementById('contact-details-div'))
document.getElementById('contact-details-div').style.display = 'none';
}
function closePopUpsBody(e){
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3)
targ = targ.parentNode;
while (targ.parentNode) {
if (targ.className && targ.className == 'closebtn')
break;
if (targ.className && targ.className == 'contact-profile-popup')
break;
targ = targ.parentNode;
}
if ((targ.className && targ.className == 'closebtn')
|| !(targ.className && targ.className == 'contact-profile-popup')) {
if(document.getElementById('contact-details-div'))
document.getElementById('contact-details-div').style.display = 'none';
document.body.onclick = null;
}
}
This code may be ugly, but this is not the main problem ...
The main problem is when I attach an event to the body, it runs immediately! and the div disappears immediately, I don’t even see it.
<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
document.body.onclick = closePopUpsBody;
return false;">
i though if i don't use parentheses it won't execute?
document.body.onclick = closePopUpsBody(); //this executes
document.body.onclick = function(){closePopUpsBody()}; //this is not
document.body.onclick = closePopUpsBody; //this is not
I finally finished with this solution
<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
setTimeout('document.body.onclick = closePopUpsBody;', 500);
return false;">
but I think this is crazy. so what am i doing wrong?
source
share