I have a search button on the page, and when users press the search button, the search bar comes into the screen and I would also like to set the input to focus as well. Can I do this with pure CSS3?
Here is the code:
<input type="checkbox" id="Search_Button" /> <!-- Opens Search Bar -->
<label for="Search_Button">
<div id="Search_Container" class="Button_Container">
<img src="SVG/Search.svg" class="Button" id="Search" />
</div>
</label>
Here you can see the CSS styling so that the search bar is pushed off the screen:
#Search_Box {
position: absolute;
width: 100vw;
height: 8vh;
background-color: #38D1A9;
transform: translate3d(0, -8vh, 0);
transition: transform .2s ease-out;
}
Here is the search box that drops down:
<div id="Search_Box">
<input type="search" name="Search" id="Search_Input" placeholder="Search" />
</div>
So here is the issue. I have a search icon displayed. When the search icon is pressed, it brings down the "Search_Box" which has the search input inside it. I would like to, when that search icon is pressed, immediately make that search box focused.
The issue with a label technique is that, while it works exactly as intended, the search icon is already inside a label (this label it sits inside is to bring down the search box into view), so I won't be able to wrap it in another label.
I tried to do this:
#Search_Button:checked ~ div #Search_Input {
cursor: pointer;
}
I tried saying that when the Search_Button was checked, it would bring the search input to focus, but it's definitely not the way to do it. I'm trying to avoid using JS if I can because I'm working on mobile.
I really apologize for any confusion!
You can achieve this with native HTML behavior by associating a label
element with the input
element. Set the label
element's for
attribute equal to the input
element id
attribute value. When the label
element is clicked, the input
element will be focused on.
label {
-webkit-appearance: button;
-moz-appearance: button;
appearance: button;
padding: 1px 6px;
}
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
It's worth mentioning that the CSS above isn't required. It was only added to make the label
element appear at a button. Feel free to style the label
element however you want. In certain cases, you can even wrap it around other elements.
Alternative example with different styling:
label {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
<label for="focus-input">Button</label>
<p>Other elements...</p>
<input type="text" id="focus-input" />
document.querySelector('button').addEventListener('click', function () {
document.getElementById('focus-input').focus();
});
<button>Button</button>
<p>Other elements...</p>
<input type="text" id="focus-input" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With