Insert a Font Awesome icon inside an input field

Recently, I ran into a minor issue while working on my login page. I wanted to include 2 fontAwesome icons just like in the example image:

https://i.sstatic.net/NweVp.png

However, after checking W3C guidelines, I discovered that placeholders cannot be used in certain input elements. To address this, I wrote a simple vanilla JS script to target the ID of each input box and assign a placeholder dynamically.

The challenge arose when trying to style these placeholders using 'font-family: "fontAwesome";'. Despite my attempts to store the JS code in a variable for styling purposes, it didn't yield the desired outcome. So, the question remains - what is the most common solution to this dilemma? Should I consider using an image instead?

This snippet showcases part of my code where placeholders are being assigned through JS:

let x = document.getElementById("mdp2").placeholder = "   Mot de passe...";
let y = document.getElementById("username").placeholder= "   Nom d'utilisateur ou e-mail...";
* {
  padding: 0;
  margin: 0;
  text-decoration: none;
  font-family: "Play", sans-serif;
  box-sizing: border-box;
}
h1,
h2 {
  font-family: "Varela Round", Arial, Helvetica, sans-serif;
}
.compte {
  position: relative;
  width: 100%;
  height: 1500px;
  overflow: hidden;
  background : orange;
}
(complete CSS code here...)
<!DOCTYPE html>
(complete HTML code here...)
</html>

Visit my CodePen

Your insights and suggestions would be greatly appreciated!

Answer №1

const inputArea = document.querySelector('.input');
const placeholderElement = inputArea.querySelector('.placeholder');
const inputElement = inputContainer.querySelector('input');

inputElement.addEventListener('focus', () => {
  placeholderElement.style.display = 'none';
  inputElement.focus();
});

inputElement.addEventListener('blur', () => {
  if (inputElement.value.trim().length === 0) {
    placeholderElement.style.display = 'block';
  }
});

placeholderElement.addEventListener('click', () => {
  placeholderElement.style.display = 'none';
  inputElement.focus();
});
.input {
  position: relative;
}

.input .placeholder {
  position: absolute;
  top: 8px;
  left: 10px;
  color: #444;
}

input {
  outline: none;
  border: 1px solid #CCC;
  border-radius: 17px;
  padding: 10px;
  height: 10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>

<div class="input">
  <div class="placeholder"><i class="fa fa-user"></i>&nbsp;Username</div>
  <input type="text" />
</div>

Answer №2

If you want to customize the appearance of your input and icon, you can add your own CSS code to achieve this effect. Check out the demo below for more details:

TIP: The idea is to enclose both the input field and the icon within a wrapper div. Apply a border to the wrapper and remove the border and outline from the input field.

.search{
  display:inline-flex;
  border:1px solid #777;
  padding:5px 10px;
  border-radius:1rem;
}

.search input{
  border:none;
  outline:none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" rel="stylesheet"/>

<div class="search">                       
 <i class="fas fa-search"></i>
 <input type="text" placeholder="Search...">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to resolve an undefined variable error in PHP?

I have a webpage named index.php. This page is designed to implement infinite scrolling using AJAX, PHP, and MySQL. The PHP MySQL codes are located at the top while JavaScript is placed at the bottom. I am trying to display the total number of rows in th ...

What is the best way to organize the size of multiple files into a single HTML card?

Is there a way to automatically arrange multiple items (photos/videos) within a single HTML card, similar to how it is done on Facebook or Instagram? I am looking for a library or JavaScript code that can help me achieve this without extending the size of ...

Update the form action URL when a specific option is selected from the dropdown menu upon clicking the submit

I would like my form to redirect to a specific page on my website based on the selection made in the <select> tag. For instance, if '2checkout' is selected, it should go to gateways/2checkout/2checkout.php. Similarly, if 'Payza' i ...

activate the bootstrap popover by double-clicking instead of a single click

Clicking on a certain div triggers a popover to display another div, which works initially. However, once the popover is removed by clicking outside the div, it requires two clicks to trigger the popover again. How can this be fixed so that it always works ...

What could be causing the issue of JavaScript not being executed when an HTML file is converted from a string?

Working on a current project involves dealing with a DB2 database that houses an email template string of around 20,000 characters containing the HTML used for constructing forms. Previously, making changes to the string and reinserting it into the table ...

Top jQuery Extension for Latest Updates

I need to display 10 images with corresponding numbers (1,2,3,4,5...). Specifically, I am looking for a jQuery plugin that allows for an image slideshow with numbered navigation. Any recommendations? ...

How can I retrieve values from HTML5 data attributes using Selenium in Python?

How can I extract the value "165796011" from data-gbfilter-checkbox? I attempted to do so using the following code: element= driver.find_element_by_css_selector('#widgetFilters > div:nth-child(1) > div.a-row.a-expander-container.a-expander-inl ...

Scan the barcode with the reading device and then input it into

I'm exploring a method to transform a return function into a tab, or vice versa. My goal is to have the user scan a barcode, which would then move them to the next text field. Finally, when they reach the last field, the form should be submitted. I&ap ...

Tips for employing the slice approach in a data-table utilizing Vue

I have a unique situation in my Vue app where I'm utilizing v-data table. The current display of data in the table works fine, but I now want to enhance it by incorporating the slice method. Here is the current data displayed in the table: https://i ...

The controller is unable to provide the output in JSON format within the AJAX response

My task requires me to continuously call and fetch data from a REST API every second. To achieve this, I am calling the method with a time interval of 1 second as shown below: var myVar = setInterval(function(){ getData1() }, 1000); Below is the JavaScri ...

Tips for eliminating empty trailing values and Carriage Returns from a JavaScript array

I needed a way to eliminate empty elements and Carriage Returns from the end of an array. Here's an example of what my array looks like: Input arr: ['', 'Apple', '', 'Banana', '', 'Guava', & ...

Discovering the state of a checkbox element in Java and Selenium can be a challenge, especially when the element is not identified as a checkbox even with the

I'm currently creating test scenarios for the aviasales.com website and I am attempting to confirm the status of a checkbox. Locating and clicking on the checkbox was simple using the following code: WebElement checkboxValue = driver.findElement(By ...

jQuery fails to execute in ajax success function

Currently, I am using jQuery and Ajax to dynamically populate a select element. However, I am facing an issue within my success callback where my DOM manipulation is being ignored. An interesting observation is that even though my console.log('test&a ...

Strange Behavior When Floating Right in Chrome

There's a strange issue that I'm facing, only in Chrome. It seems to be adding some extra space on top of an element with float: right, but only when the browser window is resized (you can see how the name then shifts under the header): This pro ...

Tips for customizing and removing single entries in a CRUD application

I am currently working on developing a CRUD app, but I am facing challenges in editing and deleting individual items. In my implementation, I have two <a> tags within a <span> tag for each created item - one for editing and one for deletion. Ho ...

Manipulating text within a specified DIV using CSS

Is there a recommended method for truncating text within a DIV using CSS? For instance, how can I ensure that the word 'TESTING' remains within the boundaries of the DIV displayed below? Currently, the text overflows beyond the DIV's height, ...

Simple steps to manipulate HTML content within a span element using JavaScript

I'm currently working on an online bus seat booking system and I've hit a roadblock with one feature. When a user selects more than one bus seat, the corresponding seat numbers should be displayed in a span or div, separated by commas. If the use ...

Blazor Server: Seamless breadcrumb navigation updates with JavaScript on all pages

I have implemented a breadcrumb feature in my Blazor Server project within the AppLayout that functions for all pages: <ul id="breadcrumbs" class="breadcrumbs"> <li><a href="#">Home</a></li> ...

The message vanishes upon refreshing the page

I've developed a socket.io web app. When I click on the button to send a message, the message appears briefly but disappears when the page refreshes unexpectedly. How can I prevent this random refreshing and ensure that socket.io saves my messages? B ...

The tailwindcss gradient text is getting cropped at the bottom

While experimenting with tailwindcss, I attempted to create a gradient text effect but noticed that the bottoms of certain letters were getting cut off. Characters like 'g' or 'p' that extend below the baseline were being partially obs ...