I'm trying to implement a Vanilla JS Dropdown menu with checkbox options. I'm able to create the dropdown and click on the labels for the options while keeping the menu open. To close the menu, I can perform a blur event or select the dropdown input again. However, when I click on the actual <input type="checkbox">
within the dropdown menu, the menu closes immediately. I would like the menu to remain open until the user closes it on blur. A clue may be coming from an error message I'm getting in the console saying that the "currentTarget is undefined" when clicking on one of these checkboxes. Any help is greatly appreciated.
Codepen: https://codepen.io/jon424/pen/MWXpPmZ?editors=1111
HTML
<div class="center">
<form tabindex="0" onclick="showCheckboxes()" onblur="hideCheckboxes()">
<div class="multiselect">
<div class="selectBox">
<select>
<option>Select an Option</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label><input type="checkbox" class="checkbox-option" id="1"/>One</label>
<label><input type="checkbox" class="checkbox-option" id="2"/>Two</label>
<label><input type="checkbox" class="checkbox-option" id="3"/>Three</label>
</div>
</div>
</form>
</div>
CSS
.multiselect {
margin: auto;
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
JS
//multi-select dropdown menu
let expanded = false;
function showCheckboxes(e) {
let checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
function hideCheckboxes(e) {
let checkboxes = document.getElementById("checkboxes");
let label = document.getElementsByTagName("label");
let input = document.querySelector("label > input");
let multiSelect = document.getElementsByClassName("multiselect");
if (
!e.currentTarget.contains(multiSelect) ||
!e.currentTarget.contains(checkboxes)
) {
checkboxes.style.display = "none";
expanded = false;
}
}
Aucun commentaire:
Enregistrer un commentaire