How to create fullscreen search bar using HTML , CSS and JavaScript ?
To create a fullscreen search bar using HTML, CSS, and JavaScript, you can follow these steps:
- Create the HTML structure for the search bar:
<div class="search-container">
<form action="#">
<input type="text" placeholder="Search...">
<button type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
- Style the search bar using CSS:
.search-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.search-container form {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
.search-container input[type="text"] {
padding: 10px;
width: 70%;
border: none;
border-radius: 5px 0 0 5px;
outline: none;
}
.search-container button {
width: 30%;
padding: 10px;
background-color: #333;
color: #fff;
border: none;
border-radius: 0 5px 5px 0;
cursor: pointer;
}
.search-container button:hover {
background-color: #444;
}
- Add JavaScript to toggle the search bar:
const searchContainer = document.querySelector('.search-container');
const searchInput = document.querySelector('input[type="text"]');
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
searchContainer.classList.remove('active');
searchInput.value = '';
}
});
document.querySelector('button').addEventListener('click', function() {
searchContainer.classList.toggle('active');
searchInput.focus();
});
- Style the search bar when it is active:
.search-container.active {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
.search-container.active form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.search-container.active input[type="text"] {
background-color: #fff;
color: #333;
}
.search-container.active button {
background-color: #fff;
color: #333;
}
Now, when the user clicks on the search button, the search bar will appear in fullscreen mode with a semi-transparent background. The user can type in their search query and press Enter to submit the form. They can also press the Escape key to close the search bar.