ArticleZip > Clear Icon Inside Input Text

Clear Icon Inside Input Text

Adding a clear icon inside an input text field can be a handy feature that enhances the user experience of your web forms. When users input information into a text field, having a clear icon allows them to easily erase or reset the content with a single click. In this guide, we will walk you through how to implement a clear icon inside an input text field using HTML, CSS, and JavaScript.

### Step 1: Create the HTML structure
Let's start by setting up the HTML structure for the input text field that will include the clear icon button. You can create a simple input field like this:

Html

<button id="clearBtn">Clear</button>

### Step 2: Style with CSS
Next, we'll style the input field and the clear icon button using CSS. Here's an example of how you can style them:

Css

#clearBtn {
  display: none;
  background: transparent;
  border: none;
  cursor: pointer;
}

#myInput:focus~#clearBtn {
  display: block;
}

### Step 3: Add JavaScript functionality
To make the clear icon button functional, we'll use JavaScript to clear the input field when the button is clicked. Add the following JavaScript code to your file:

Javascript

const input = document.getElementById('myInput');
const clearBtn = document.getElementById('clearBtn');

clearBtn.addEventListener('click', () =&gt; {
  input.value = '';
});

### Final Touches
Now, when a user types something in the input field, the clear icon button will appear on focus, and clicking it will clear the input field content instantly. You can further customize the styling and behavior according to your project's requirements.

By following these steps, you can easily implement a clear icon inside an input text field on your website or web application. This small but useful feature can greatly improve the usability of your forms and provide a smoother user experience.

We hope this guide has been helpful in showing you how to add a clear icon inside an input text field using HTML, CSS, and JavaScript. Try implementing this feature in your next project and see the positive impact it has on user interactions.

×