I need to hide the dropdown by clicking anywhere on the screen when the dropdown is displayed.
How can I do?
Steps
1-click the label dropdown 2-Click anywhere on the screen
Expected behavior
The dropdown disappears
Current behavior
The dropdown is displayed This is my code:
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.globalContainer{
margin-left: 400px;
}
.dropdown-content-desactivate {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown-content-activate {
display: block;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
</style>
<script>
function chooseOption(label){
document.getElementById("optionSelected").innerHTML = label;
document.getElementById("contentDropdown").className = "dropdown-content-desactivate";
}
function showDropdownContent(){
document.getElementById("contentDropdown").className = "dropdown-content-activate";
}
</script>
</head>
<body>
<div class="globalContainer">
<div class="dropdown" >
<span onclick="showDropdownContent()">dropdown</span>
<div id="contentDropdown" class="dropdown-content-desactivate ">
<div onclick="chooseOption('option 1')">option 1</div>
<div onclick="chooseOption('option 2')">option 2</div>
<div onclick="chooseOption('option 3')">option 3</div>
<div onclick="chooseOption('option 4')">option 4</div>
</div>
</div>
<div class="backgroundDropdownactivado"></div>
<br>
<br>
<br>
<br>
<br>
<br>
<span>La opcion selecionada en el dropdown es:</span><span id="optionSelected"></span>
</div>
</body>
</html>