Creating an animated search bar in just a second may sound impossible, but with some CSS and JavaScript skills, you can achieve this in no time! In this tutorial, I will guide you step-by-step on how to create an eye-catching animated search bar for your website.
Let’s get started!
Step 1: Set up your HTML structure
First, create a new HTML file and set up the basic structure of your webpage. Add a div element with a class of "search-container" where we will create our animated search bar.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Animated Search Bar</title>
</head>
<body>
<div class="search-container">
<input type="text" placeholder="Search...">
<button id="search-btn">Search</button>
</div>
<script src="script.js"></script>
</body>
</html>
Step 2: Style your search bar with CSS
Next, create a new CSS file and style the search container, input field, and button. Here, we will use CSS animations to create the animated effect.
.search-container {
position: relative;
width: 300px;
margin: 50px auto;
}
input[type="text"] {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
outline: none;
}
button {
position: absolute;
right: 5px;
top: 5px;
padding: 10px;
border: none;
background-color: #007bff;
color: #fff;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
/* CSS animation */
.search-container:focus-within input[type="text"] {
width: 250px;
transition: width 0.5s;
}
Step 3: Add JavaScript for functionality
Finally, create a new JavaScript file and add functionality to toggle the width of the input field when the search container is focused.
const searchContainer = document.querySelector('.search-container');
const inputField = document.querySelector('input[type="text"]');
searchContainer.addEventListener('focusin', () => {
inputField.style.width = '250px';
});
searchContainer.addEventListener('focusout', () => {
inputField.style.width = '100%';
});
And that’s it! Your animated search bar is now ready to use. When you click on the search container, the input field will expand to 250px width with a smooth animation, giving a stylish look to your website.
Feel free to customize the styles and animations to match your website design. You can also add more advanced animations and effects using CSS and JavaScript libraries to make your search bar even more interactive.
I hope you found this tutorial helpful in creating an animated search bar in just a second. Have fun experimenting with different animations and designs to enhance your website’s user experience!