Jump to content

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


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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.