Jump to content

Trying to hide element if clicked out of the div? So simple but so hard..


Monkuar

Recommended Posts

I am trying to hide the menu if a user has clicked outside of the div (Menu)

 

 

 

 

 

function pe(a){return document.getElementById(a)}



function CngClass(obj) {
obj.className = 'userinfo radius2 userinfodrop'; // Shows the menu/etc
    pe('show').id = 'show2'; //Shows menu
var open = true;
}
document.onclick=function(){
if (open == true){
//Close the div or try to...
pe('show2').style.display='none';
}
}

 

Okay, so pretty much when they onclick="CngClass" it will make the element id ('show') to show2, which will show the menu.  And set a var open to true right? Now if they click anywhere on the document, I want to check if open == true, to hide the div....................

 

 

It's pretty stupid how I set the var open = true and it still doesn't even recognize it after, pretty pathetic if you ask me. 

I dont want to waste anyones time, but I found a solution..

 

function hide(id) {
elm = document.getElementById(id)

elm.style.display == "none" ? elm.style.display = "block" : elm.style.display = "none"
}

document.onmousedown = function() {
hide('show2')
}

 

topic solved..

 

sorry for me being a comlpete jew

 

 

edit: wait, no unsolved because they can just click and it will toggle it.. sht.............

You can do this with a little DOM event trickery. Knowing that events bubble up through the DOM tree, the idea is to bind a click event to the document that will always hide it, but then another event on the menu wrapper that will intercept events bubbling up and stop the propagation.

 

That way any click events originating from within the menu, will travel up the DOM tree until they hit the wrapper's click handler and then stop. Any click events originating from outside of the menu will travel all the way up to the document and so hide the menu.

 

Just be sure to only bind this behaviour when the menu is showing, and then unbind it when it's hidden.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.