This is a simple input field which is over a button, which translate in X axis to =70px and the button underneath becomes visible, I am using z index to keep them on top of each other and pseudo class :focus is used to animate the affect.The problem is I am unable to click on the button to call the function
function fetch(){
alert('Clicked');
}
.fetch-container{
margin: 20px;
position: fixed;
top : 50vh;
left: 45vw;
}
body{
background-color: rgb(223, 222, 222);
}
.search-input{
position: absolute;
top: 0px;
left: 0px;
padding: 10px;
border-radius: 25px;
border-style: none;
z-index: 2;
}
.search-input:focus{
outline: none;
transform: translateX(-70px);
}
.search-button{
position: absolute;
top: 0px;
left: 70px;
padding: 10px 5px 10px 50px;
border-radius: 25px;
border-style: none;
width: 120px;
z-index: 1;
}
.search-button:hover{
background-color: #FFC26F;
}
<div class='fetch-container'>
<div>
<input class='search-input' type='text' placeholder='Please Enter your City'/>
<button type='submit' class='search-button' onClick="fetch()">Check</button>
</div>
</div>
Codepen link : https://codepen.io/Roronoa-Zoro-the-selector/pen/YzRVgjz
tried pointer-events: visible
/none
etc
2
Answers
The problem comes from the
:focus
style block being cancelled (near) instantaneously when the search field loses focus. As the button can’t be clicked while the search field has focus, and is unexposed unless the search field has focus, the button is never available to receive a click event.As far as I know, there is no way for the transformation to persist after the focus is lost using your css approach.
A work-around would be to remove the
:focus
css block and instead perform the translation by amending the style through javascript. When javascript sets a style rule, it persists until another command changes it, allowing the button to remain exposed after the search field has lost focus.This is done by first creating a reference to the search box in javascript:
and then setting an event listener to add the translation style in response to the search field gaining focus:
The translated position persists after the search field loses focus making the button available to click.
Working snippet:
Don’t forget to remove, or comment out, the
:focus
css block:The button isn’t clicked because it has a z-index lower that that of the search input element and so is behind the search input element at the time it is clicked.
A fix, however would be to change the z-index of the button when it is hovered over like so:
But then you would have to change some aspects of the design as well