Currently, I've come across a strange issue in javascript while working with the .focus()
function and css transitions.
Check out the jsFiddle link below for reference.
In my setup, there's a modal containing a search input field. Upon clicking on the #trigger
, a class is added to the modal along with a focus()
event triggered on the input field (to enhance user experience).
This approach was functioning perfectly until... I decided to implement CSS transitions to provide a smoother appearance (applied on the opacity
and visibility
properties).
Any insights on where this complication might be originating from?
Thank you in advance!
let trigger = document.getElementById('trigger'),
closer = document.getElementById('closer'),
box = document.getElementById('wrapper'),
sInput = document.getElementById('search__input')
trigger.addEventListener('click', () => {
box.classList.add('is-visible')
sInput.focus()
})
closer.addEventListener('click', () => {
box.classList.remove('is-visible')
})
#wrapper {
position: fixed;
top: 0; left: 0; right: 0;
width: 100%; height: 100%;
background: rgba(0, 0, 0, 0.8);
visibility: hidden;
opacity: 0;
transition: opacity .1s linear, visibility .1s linear .1s;
}
#wrapper.is-visible {
opacity: 1;
visibility: visible;
transition: visibility .1s linear, opacity .1s linear .1s;
}
#closer {
position: absolute;
top: 10px; left: 10px;
color: #000;
background-color: white;
}
#search__input {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
font-size: 24px;
}
<a href="#" id="trigger">Click me.</a>
<div id="wrapper">
<a href="#" id="closer">Close me.</a>
<input type="search" placeholder="Search here" id="search__input"/>
</div>
Similar approach without utilizing CSS transitions
let trigger = document.getElementById('trigger'),
closer = document.getElementById('closer'),
box = document.getElementById('wrapper'),
sInput = document.getElementById('search__input')
trigger.addEventListener('click', () => {
box.classList.add('is-visible')
sInput.focus()
})
closer.addEventListener('click', () => {
box.classList.remove('is-visible')
})
#wrapper {
position: fixed;
top: 0; left: 0; right: 0;
width: 100%; height: 100%;
background: rgba(0, 0, 0, 0.8);
visibility: hidden;
opacity: 0;
}
#wrapper.is-visible {
opacity: 1;
visibility: visible;
}
#closer {
position: absolute;
top: 10px; left: 10px;
color: #000;
background-color: white;
}
#search__input {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
padding: 10px;
font-size: 24px;
}
<a href="#" id="trigger">Click me.</a>
<div id="wrapper">
<a href="#" id="closer">Close me.</a>
<input type="search" placeholder="Search here" id="search__input"/>
</div>