What is the method for applying background color to text within a textbox?

I am struggling to phrase this question properly and unable to find the solutions I need on Google. When searching, it only provides information on how to add an entire background color to a textbox, which is not what I am looking for. What I aim to achieve are results similar to the image linked below:

https://i.sstatic.net/1g4Ch.png

The goal is to add a background color to each individual character within an input tag, excluding spaces. As the user types inside the input tag, the characters should be highlighted with a background color but not the spaces.

Currently, I do not have any code as I am unsure of how to implement this using CSS or JavaScript if necessary. All I have is an

<input type="text">

My intuition tells me that JavaScript may be the solution, but I am uncertain of how to proceed (despite having knowledge of JS). How can I accomplish this task?

Answer №1

You could implement a contentEditable div element and utilize some JavaScript to insert text as spans.

<div contentEditable></div>

Here is the CSS styling:

span {
  background-color: red;
  margin-right: 2px;
}
div {
  border: 1px solid black;
}
var el = document.querySelector("div");

el.addEventListener("blur", () => {
  var content = el.textContent;
  var contents = content.split(" ");
  el.innerHTML = "";

  contents.forEach((item) => {
    el.innerHTML += `<span>${item}</span>`;
  });
});

This approach can help achieve something similar to this example.

Answer №2

To implement the "mirroring" technique with precision, you can create an overlap between the input box and a mirrored element. The layout and text characteristics must match perfectly for this method to work effectively. Below is a simple example code snippet to demonstrate how this can be achieved:

const userInput = document.getElementById("user-input"),
  mirrorElement = document.getElementById("input-mirror");

userInput.addEventListener("keyup", function() {
  const wordsArray = userInput.value.split(" ").map(function(term) {
    const wordSpan = document.createElement("span");
    wordSpan.textContent = term;
    return wordSpan;
  });
  
  mirrorElement.innerHTML = "";
  
  for (let j = 0; j < wordsArray.length; j++) {
    mirrorElement.append(wordsArray[j], " ");
  }
});
.container {
  display: grid;
}

#user-input,
#input-mirror {
  font: inherit;
  box-sizing: border-box;
  margin: 0;
  border: 1px solid;
  padding: 0;
  grid-row: 1;
  grid-column: 1;
}

#user-input {
  background: transparent;
}

#input-mirror > span {
  background: #0f0;
}
<div class="container">
  <span id="input-mirror"></span>
  <input id="user-input" type="text" />
</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

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

AngularJS search box functionality allows users to easily search through a

1 I am looking to develop a search box using AngularJS similar to the one shown in the image. While I am familiar with creating a normal text box, I am unsure of how to incorporate the search icon. Any guidance on how to achieve this would be greatly appr ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

What other function can I combine with the foreach function?

I am working on populating the empty array named $Errors with specific items to enforce restrictions on my file upload form. My approach involves adding a <div> element as an item within the array, containing certain strings. I aim to concatenate t ...

What is the best way to eliminate the background color from one span after selecting a different one?

I created a span element that changes its background color when clicked, but I want the background color to switch to the newly clicked span while removing it from the previously clicked one. Can someone help me achieve this? CSS list-sty ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

What is the best way to combine text from various group radio buttons?

Here is the JavaScript code I have written: $(function(){ $('input[type="radio"]').click(function(){ var txt = $(this).parent().text(); var $radio = $(this); if ($radio.data('waschecked') == true) { ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Using InnerHTML in Javascript within the Quasar/VueJS framework is unsupported

I am looking to dynamically create tables based on the items inside the 'counts' array below. The number of tables and their contents can change. Here is my divContainer, where the innerHTML will be appended: <div id="divContainer" style="pa ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

How can I code a div to automatically scroll to the top of the page?

I'm attempting to implement something similar in WordPress - I want a div containing an advertisement to initially start 300px down the page, then scroll up with the page until it reaches the top, and finally stay there if the user continues to scroll ...

What is the best way to update a data value in one Vue Js component and have it reflected in another component?

I'm a newcomer to Vue Js and encountering an issue with changing data values from another component. Let's start with Component A: <template> <div id="app"> <p v-on:click="test ()">Something</p> </div> ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

AngularJS restricts the display of elements to only 4 using the limitTo filter

I'm facing an issue with my filters. I have a JSON dataset that I need to display on my website, but I only want to show 4 elements that meet a certain criteria. Here's the code snippet: <div ng-repeat="place in places | limitTo: 4 | filter: ...

Matching up irregular rows in div-made table

I have created a table using div elements that contain images as cell data. When an image is missing, I would like to center the remaining images in the row like this: With all images present: xxxxx xxxxx Missing images (2 in the second row): xxxxx xx ...

Enhancing w3-import-html with JavaScript

<div id="import" includeHTML="page.html"></div> function getInclude() { var x = document.getElementById("import").includeHTML; //returns 'undefined' alert(x); } function modInclude() { document.getElementById("import") ...

Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task? The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum o ...

Finding the correct tablet browser resolution for optimal web design

Is there a way to accurately determine the browser resolution for CSS on Samsung Galaxy Tab A 10.1 or other tablets? Despite the specifications stating that the resolution is 1920 x 1200, I am having trouble finding the correct resolution online. As I hav ...

Having trouble releasing the package on npm platform

I'm facing difficulties in publishing a public package to npm. Despite creating an organization, I'm unable to figure out how to add a new package. Any assistance on this matter would be greatly appreciated. https://i.sstatic.net/RMKU9.png ...

Altering an element's visibility from 'none' will trigger its animation to play once again

Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue) ...