I am currently working on designing a custom selection menu using HTML, CSS, and JavaScript. The concept is simple: there is a div element styled to look like an input field that, when clicked, reveals another div containing a list of options. The user can then select an option from the menu, causing it to hide and the chosen entry to appear in the input div. However, I have encountered an issue where subsequent clicks on the input div do not reopen the menu div.
This is the HTML code I have written:
<div id="destination">
<div class="list">
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body1</p>
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body2</p>
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body3</p>
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body4</p>
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body5</p>
<p class="body" onmouseover="highlight(this)" onmouseleave="back(this)" onclick="select(this)">Body6</p>
</div>
</body>
Here is my CSS styling:
#destination{
margin: 10% auto;
width: 14.15em;
height: 2em;
border: 1px solid black;
box-sizing: border-box;
background: transparent;
}
.list{
display: none;
width: 10em;
height: 5em;
overflow:scroll;
border: 1px solid black;
padding: .5em;
background:white;
position: relative;
left: 10.5%;
top:-105%;
}
.body{
display: block;
text-align: center;
margin:0;
padding:.25em;
}
.visible{
display:inherit;
}
And this is the JavaScript part of the code:
// identify the input div
let destination= document.getElementById('destination');
// identify the menu div
let list= document.querySelector('.list');
// show or hide the menu div upon click event
destination.addEventListener('click',function(){
list.classList.toggle('visible');
});
// functions for highlighting entries
function highlight(elem){
elem.style.cssText = "background: rgba(0,0,0,0.3); transition: background .5s linear";
}
function back(elem){
elem.style.cssText = "background: inherit; transition: background .5s linear";
}
// upon selecting an option, hide the menu div and update the input div with the selected entry
function select(elem){
list.classList.toggle('visible');
destination.innerHTML = elem.innerText;
destination.style.cssText = "padding-top: .35em; padding-left: 5.75em;"
}
Despite not receiving any error messages from the browser console, I am struggling to resolve the issue with the menu not reopening after the first click on the input div.