Click Outside Close Menu Box JavaScript

Hello,

I had written a code to close the menu when clicking outside, but it's not working can anyone tell what's wrong in my code.

Code:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<style>
#box1{
    Position:absolute;
    left: 10px;
    top: 10px;
    width:200px;
    height:200px;
    padding:10px;
    color:#000;
    font: bold 12px Arial, Helvetica, sans-serif;
    background: #ccc;
    display:none;
}

.button{
    width:120px;
    padding:10px;
    margin-right:10px;
}
</style>
</head>

<body>
<div id="box1">
<h2>Content Box1</h2>
<p>If you are interested in hiding content via JavaScript and not necessarily deleting or removing them from the DOM, see my post on How to Hide and Show Your Div.</p>
</div>

<h2> Click on the below buttons</h2>
<button class="button" onclick = "document.getelementById('box1').style.display='block'">Box1</button>
<script>
window.addEventListener('mouseup', function(event){
    var box = document.getElementById('box1');
    if (event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
});
</script>
</body>
</html>

Hi there koder,

this…

document.getelementById('box1')
…should be…

document.getElementById('box1')

You could code the page like this perhaps…

[code]

Untitled Document #box1{ width:200px; height:200px; padding:10px; color:#000; font: bold 12px Arial, Helvetica, sans-serif; background: #ccc; } .button{ width:120px; padding:10px; margin-right:10px; } .hide { display:none; }

Click on the below buttons

Box1

Content Box1

If you are interested in hiding content via JavaScript and not necessarily deleting or removing them from the DOM, see my post on How to Hide and Show Your Div.

[/code]

coothead

Thanks very much coothead, it’s working now.

 

        No problem, you’re very welcome. :smile:

coothead

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.