How to Build an Animated Search Bar with HTML, CSS, & JS

Have you ever seen modern websites with search bars that start as a clean, small circular button and expand smoothly into a full input field when clicked? This UI component is popular because it saves valuable screen real estate while giving users a sleek, interactive experience.

In this tutorial, we will break down a simple recipe to build an expandable search bar using clean HTML, pure CSS, and a dash of JavaScript.

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Basic HTML Document Setup & Viewport Configuration -->
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Expandable Animated Search Bar - Commented Tutorial</title>

    <link rel="stylesheet" href="style.css" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
    />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300;400;500;600;700&display=swap"
      rel="stylesheet"
    />

  </head>
  <body>
    <!-- Main Flexbox Wrapper -->
    <div class="container">
      <!-- Search Bar Component Wrapper -->
      <div class="search-bar">
        <!-- Input Text Field -->
        <input type="text" placeholder="Type here..." />
        
        <!-- Search Icon (Magnifying Glass) - Active when collapsed -->
        <i class="fa-solid fa-magnifying-glass"></i>
        
        <!-- Close Icon (X Mark) - Active when expanded -->
        <i class="fa-solid fa-xmark"></i>
      </div>
    </div>
        <script src="script.js"></script>
  </body>
</html>

/* 
        ==========================================================================
        1. GLOBAL RESET & BASE STYLES
        ==========================================================================
      */
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box; /* Includes padding and border in total width/height */
        outline: none;
      }

      /* 
        Base font size set to 62.5% converts 1rem to 10px (assuming default 16px browser root).
        Simplifies rem unit sizing calculations (e.g., 8rem = 80px, 45rem = 450px).
      */
      html {
        font-size: 62.5%;
      }

      /* 
        Full-screen flexbox container centering the search bar component.
        Modifying 'background-color' changes the page theme.
      */
      .container {
        width: 100%;
        height: 100vh;
        background-color: #161a1d;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      /* 
        ==========================================================================
        2. SEARCH BAR CONTAINER STYLES & ANIMATIONS
        ==========================================================================
      */
      /* Collapsed State: A small circular button shape (8rem x 8rem) */
      .search-bar {
        width: 8rem;
        height: 8rem;
        text-align: right;
        background-color: #fff;
        border-radius: 10rem;
        box-shadow: 0 1rem 6rem rgba(0, 0, 0, 0.6);
        position: relative;
        /* Smooth cubic-bezier transition curve applied when width changes */
        transition: width 0.5s cubic-bezier(0.9, 0, 0.3, 0.9);
      }

      /* Expanded State: Triggered when JavaScript adds the '.change' class to .container */
      .change .search-bar {
        width: 45rem; /* Adjust this value to change the expanded search bar length */
      }

      /* 
        ==========================================================================
        3. INPUT FIELD STYLING
        ==========================================================================
      */
      .search-bar input {
        width: 100%;
        height: 100%;
        border-radius: 5rem;
        border: none;
        background-color: transparent;
        padding: 1rem 7.5rem 1rem 2rem;
        font-family: "Signika Negative", sans-serif;
        font-size: 2rem;
        opacity: 0; /* Hidden by default when collapsed */
        transition: opacity 0.5s;
      }

      /* Fades in the input field when expanded, with a 0.3s delay to sync with width expansion */
      .change .search-bar input {
        opacity: 1;
        transition: opacity 0.5s 0.3s;
      }

      /* 
        ==========================================================================
        4. ICON STYLING & TOGGLE ANIMATIONS
        ==========================================================================
      */
      /* Shared button styling for both magnifying glass and close icons */
      .search-bar i {
        position: absolute;
        top: 50%;
        right: 0.5rem;
        transform: translateY(-50%);
        width: 7rem;
        height: 7rem;
        background: #2ae28c; /* Accent color for icon button */
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 50%;
        font-size: 2.5rem;
        color: #fff;
        cursor: pointer;
        transition: opacity 0.3s 0.3s;
      }

      /* Hide Close Icon (3rd child) in collapsed state */
      .search-bar i:nth-child(3) {
        opacity: 0;
      }

      /* Show Close Icon when expanded */
      .change .search-bar i:nth-child(3) {
        opacity: 1;
      }

      /* Hide Search Icon (2nd child) when expanded */
      .change .search-bar i:nth-child(2) {
        opacity: 0;
      }

// Select the main container element that holds the active state class '.change'
  const container = document.querySelector(".container");

// Select both action icons (magnifying glass and close button) inside the search bar
  const searchIcons = document.querySelectorAll(".search-bar i");

 // Attach a click event listener to each icon
    searchIcons.forEach((searchIcon) => {
    searchIcon.addEventListener("click", () => {
    /*
Toggles the '.change' class on '.container':
  - If '.change' is absent: Adds class -> Expands search bar & shows close icon.
  - If '.change' is present: Removes class -> Collapses search bar & shows search icon.
  */
   container.classList.toggle("change");
   });
});

Key Ingredients

To construct this component, we need three primary files:

  1. HTML (index.html) to define the layout structure.
  2. CSS (style.css) to handle styling and smooth animation transitions.
  3. JavaScript (script.js) to manage interaction states.

Step 1: Building the HTML Skeleton

The HTML markup is kept lightweight. We set up an outer .container wrapper, a .search-bar wrapper, an <input> element, and two FontAwesome icons.

The first icon serves as the search/open button (magnifying glass), while the second icon acts as the close button (X mark).

Step 2: Adding Interactivity with JavaScript

To make the search bar respond when clicked, we use a minimal JavaScript script. Instead of writing complex logic, we simply toggle a CSS class.

JavaScript listens for a click event on the icons inside the .search-bar. When clicked, it toggles the .change class on the main .container element. This .change class serves as a state indicator determining whether the search bar is open or closed.

Step 3: Styling and Animating with CSS

This is where the visual magic happens. By default, the search bar is styled as a small circle measuring 8rem by 8rem. The input element is initially hidden by setting its opacity to opacity: 0.

When the .change class is active:

  • The .search-bar width expands smoothly to 45rem.
  • The cubic-bezier(0.9, 0, 0.3, 0.9) easing curve creates a springy, modern motion feel.
  • The input text fades in (opacity: 1) with a slight delay (0.3s), appearing right as the expansion completes.
  • The magnifying glass icon fades out (opacity: 0) and is replaced by the close icon (opacity: 1).

Customization Guide

You can easily adapt this component to match your project’s design system:

  • Width Size: Adjust width: 45rem in .change .search-bar if you prefer a wider or narrower search input.
  • rem Scale: The CSS sets html { font-size: 62.5%; }, meaning 1rem equals 10px. This simplifies sizing calculations across your stylesheet.
  • Color Palette: Customize #161a1d for the background and #2ae28c for the button background to align with your theme.
  • Animation Timing: Adjust 0.5s or the cubic-bezier curve on the transition properties to tweak the animation speed and feel.

Conclusion

By combining a clean HTML structure, minimal JavaScript state toggling, and modern CSS transitions, you have built a responsive and interactive search bar. Enjoy customizing and integrating it into your web projects!

Tinggalkan komentar