Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display a div below a selected input field? No JQuery

how to display a div everytime a user focus on a input field. there is already a div and it is hidden. the position of the div will change depending on the position of the selected field and it will be display below

this is my code

formFieldListWrapper.style.top = ((((formSelectedFieldInput.offsetTop > (formWrapper.offsetHeight/2))?((formSelectedFieldInput.offsetTop-(formWrapper.offsetHeight/2))-(formSelectedFieldInput.offsetHeight+formWrapper.offsetHeight*0.02)):(formSelectedFieldInput.offsetTop))/formWrapper.offsetHeight)*100) + "%";
formFieldListWrapper.style.left = ((formSelectedFieldInput.offsetLeft/formWrapper.offsetWidth)*100) + "%";
like image 482
Kevin Karl Leaño Avatar asked Aug 31 '25 10:08

Kevin Karl Leaño


1 Answers

Why use javascript? This could be chieved by using CSS only

HTML

<div class="holder">
    <input type="text" />
    <div class="dropdown">
        <p>Testing</p>
        <p>Css ONLY</p>
        <p>Dropdown</p>
    </div>
</div>

CSS

.holder {
    position: relative;
}
.dropdown {
    position: absolute;
    border: 1px solid red;
    display: none;
}

input:focus + .dropdown {
    display: block;
}

UPDATE

little bit misred the question, if You need to position div dynamically like in this fiddle, You cloud use:

HTML

<div class="holder">
    <input type="text" />

</div>
<div class="holder" style="margin-top: 30px;">
    <input type="text" />
</div>
<div class="dropdown">
    <p>Testing</p>
    <p>Css ONLY</p>
    <p>Dropdown</p>
</div>

CSS

.holder {
    position: relative;
}
.dropdown {
    position: absolute;
    border: 1px solid red;
    display: none;
    z-index: 1;
    background: white;
}

input:focus + .dropdown {
    display: block;
}

Javascript to position dropdown div

var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].addEventListener('focus', function(){
        this.parentNode.appendChild(document.querySelector('.dropdown'));
    });
}
like image 92
Bogdan Kuštan Avatar answered Sep 03 '25 00:09

Bogdan Kuštan