Wordpress Search with a Floating Form Label and a Search Icon Prefix
searchform.php
<?php
/* Custom search form */
?>
The CSS
:root {
--font-size: 1.375rem;
--font-weight: 400;
--x-pad: 2rem;
--text-indent: 2.5rem;
}
.form-group {
align-items: center;
display: flex;
position: relative;
input {
appearance: none;
font-size: var(--font-size);
font-weight: var(--font-weight);
padding: 1rem var(--x-pad);
text-indent: var(--text-indent);
transition: 250ms;
width: 100%;
}
.icon {
background-position: center;
background-repeat: no-repeat;
background-size: 1.5rem 1.5rem;
display: block;
height: 1.5rem;
left: var(--x-pad);
position: absolute;
width: 1.5rem;
&.search {
background-image: url('search.svg');
}
}
.floating-label {
color: #dee2e6;
font-size: var(--font-size);
font-weight: var(--font-weight);
position: absolute;
left: calc(var(--x-pad) + var(--text-indent));
transition: 250ms;
}
&.focused {
.floating-label {
visibility: hidden;
}
}
}
The JavaScript:
const hideFloatingLabelOnFocus = () => {
document.querySelectorAll( '.form-group' ).forEach( ( formGroup ) => {
const input = formGroup.querySelector( 'input' );
if ( input.value !== '' ) {
formGroup.classList.add( 'focused' );
}
input.addEventListener( 'focus', function () {
formGroup.classList.add( 'focused' );
});
input.addEventListener( 'blur', function () {
if ( this.value === '' ) {
formGroup.classList.remove( 'focused' );
}
});
});
}
if ( document.readyState === 'loading' ) {
// Loading hasn't finished yet, set an event listener
document.addEventListener( 'DOMContentLoaded', hideFloatingLabelOnFocus );
} else {
// `DOMContentLoaded` has already fired, run the func directly
hideFloatingLabelOnFocus();
}
Feedback?
Email us at enquiries@kinsa.cc.