Here is a simplified example of the input dropdown I am currently working on.
The functionality is as follows: when you focus on the input field, a dropdown menu appears. If you click on one of the options in the dropdown, that option gets populated in the input field and the dropdown disappears. I have implemented this using the onfocus
event along with my custom functions dropdown();
and undropdown();
.
I am facing a challenge where I need to make the dropdown disappear when someone clicks outside of it. Using the onblur
event successfully hides the dropdown, but it also prevents the input from being populated when an option is clicked. This happens because the onblur
function triggers first, making the input();
function inaccessible since the dropdown is already hidden.
If I add an onclick
event to the body or a parent element, it registers the input's onfocus
as a click, causing the dropdown to show and hide immediately without giving the user a chance to select an option.
Any guidance on how to sequence the functions properly so they execute in the correct order without conflicting with each other would be greatly appreciated.
You can access the JSFiddle demonstration here.
function input(pos) {
var dropdown = document.getElementsByClassName('drop');
var li = dropdown[0].getElementsByTagName("li");
document.getElementsByTagName('input')[0].value = li[pos].innerHTML;
undropdown(0);
}
function dropdown(pos) {
document.getElementsByClassName('content')[pos].style.display = "block"
}
function undropdown(pos) {
document.getElementsByClassName('content')[pos].style.display = "none";
}
.drop {
position: relative;
display: inline-block;
vertical-align: top;
overflow: visible;
}
.content {
display: none;
list-style-type: none;
border: 1px solid #000;
padding: 0;
margin: 0;
position: absolute;
z-index: 2;
width: 100%;
max-height: 190px;
overflow-y: scroll;
}
.content li {
padding: 12px 16px;
display: block;
margin: 0;
}
<div class="drop">
<input type="text" name="class" placeholder="Class" onfocus="dropdown(0)"/>
<ul class="content">
<li onclick="input(0)">Option 1</li>
<li onclick="input(1)">Option 2</li>
<li onclick="input(2)">Option 3</li>
<li onclick="input(3)">Option 4</li>
</ul>
</div>
PS: Besides addressing the issue mentioned above, I welcome suggestions for refining the title of this question to make it more discoverable for those facing a similar dilemma.