How can I change the background color of the initial word in a textbox?

In my HTML, I have a text box input. While I am familiar with how to use CSS to set the background color of the entire textbox using background-color, I am wondering if it is possible to specifically target and change the background color of only the first word typed. For example, if someone enters "hello there," I would like the word 'hello' to appear in orange, while typing "how are you" should make the word 'how' blue.

I was able to style the complete textbox in this JSFiddle using jQuery and CSS. However, I am seeking a way to modify the background color for just the initial word. Is this achievable?

Answer №1

Simple and quick solution (not perfect) put together in just a few minutes, but it might assist you in building a better solution.

Visit this link for the demo

HTML:

<div class="magic-input-container">
    <div class="form-control first-word"></div>
    <input type="text" id="textbox" class="form-control" placeholder="Type here..."/>
</div>

JS:

$(document).on('keydown keyup change', '.magic-input-container input', function (){

    if(($(this).val().length) && ($(this).val().split(' ').length)){

        $(this).closest('.magic-input-container').find('.first-word').html($(this).val().split(' ')[0]).show();
    }
    else{

        $(this).closest('.magic-input-container').find('.first-word').hide();
    }    
});


$(document).on('click', '.magic-input-container .first-word', function (){

    $(this).closest('.magic-input-container').find('input').focus();
});

CSS:

body {
    padding: 10px;
}

.magic-input-container {
    width: 100%;
    height: auto;
    position: relative;
    float: left;
}

.magic-input-container .first-word {
    background: red;
    width: auto;
    height: 20px;
    line-height: 20px;
    box-shadow: none;
    margin: 6px 12px;
    padding: 0px 1px;
    border: 0px;
    top: 0px;
    position: absolute;
    border-radius: 0px;
    display: none;
    color: #FFF;
}

Answer №2

As there is no specific formatting style for a textbox or textarea like this, you can create the desired effect by implementing some creative techniques. Here are two ideas:

  1. One option is to set the background color of the text input to transparent and then create a colored background using elements like span or div. Adjust the position or margin so that the text box appears on top of the background.
  2. Another approach is to write or use a formatted text editor that renders text using HTML.
$(document).ready(function() {
    $('input').keyup(function(){
        var str= $(this).val();
        var idx = str.indexOf(' ') != -1?str.indexOf(' '):str.length;
        $('span').text(str.substr(0, idx));
        $(this).css('margin-left',-$('span').width()-6);
    });    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span style="background-color:green; color:transparent">hello</span>
<input value="hello there" style="margin-left:-36px; background: transparent"/>

Answer №3

Here's my jQuery-free version of the code :)

HTML:

<div class="box">
    <span id="background"></span>
    <input id="inputField" type="text" name="textfield" size="50" />
</div>

CSS:

.box {
    position: relative;
}

.box span {
    background: blue;
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    opacity: 0.6;
}
.box input {
    position: absolute;
    z-index: 1;
}

JavaScript:

var bgElement = document.getElementById("background");
var inpElement = document.getElementById("inputField");
bgElement.style.height = inpElement.offsetHeight + "px";

inpElement.addEventListener("keyup", function() {

    var value = this.value.trim();
    var firstWord = value.split(" ")[0];
    var spanWidth = document.createElement("span");
    spanWidth.textContent = firstWord;
    spanWidth.style.display = 'none';
    document.body.appendChild(spanWidth);
    var width = spanWidth.offsetWidth - 4;
    document.body.removeChild(spanWidth);
    bgElement.style.width = width + "px";
});

Check out the demo here.

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

Tips for specifying headings for a particular div ID

I'm attempting to customize the font-family of the headings within my header section differently from the headings located elsewhere on the webpage. Unfortunately, I am encountering difficulties in ensuring that this style change only affects the spec ...

Ensuring that two operators are not consecutively placed in a Javascript calculator-validation guide

After creating a basic calculator using HTML, CSS, and JavaScript, I encountered an issue. When validating user input, the calculator currently accepts multiple operators in a row. To address this, I attempted to prevent consecutive operators by checking ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

What is the best way to implement a multi-row form in Vue.js?

Form Structure: <card-wrapper v-for="(passenger, index) in form.passenger" :key="index" :icon="['fas', 'user']" :title="`Passenger ${index + 1}`" class="mb-5" > <validation-observer ...

Using .addEventListener() within a function does not successfully generate the intended event listener

For a while, my program ran smoothly with the line canvas.addEventListener("click", funcName, false);. However, I recently realized that at times I needed to replace this event listener with another one: canvas.addEventListener("click" ...

Unselecting a span in AngularJS: Switching selection to another span

Whenever I click on an item from my list displayed using ngrepeat, it generates another list specific to the selected element. My goal is to change the background color of the clicked element to indicate it has been selected. However, the problem arises wh ...

Increment the name field automatically and track the number of auto-increment variables being sent through serialization

I am trying to implement a functionality where users can add more inputs by pressing a button, each representing an additional 'guest'. The issue I am facing is with auto-incrementing the JavaScript so that new inputs are added with an incremente ...

Encountering a 404 error while attempting to retrieve data from Node.js within a React.js application despite the server being operational

This is my first time delving into the world of back-end development, and it's quite challenging for me. The tech stack I'm using includes React.js, Node.js, express.js, and mysql. However, when I try to fetch the result of a query, I keep runnin ...

A step-by-step guide on extracting nested ASP.NET DataGrid values with JavaScript

Looking to retrieve data from a nested data grid on an aspx page using JavaScript. Check out the following code snippet: <tr> <td colspan="2" align="center"> <asp:DataGrid ID="sampleData" AutoGenerateColumns="false" runat="serv ...

Exploring the possibilities of accessing Vue.prototype within an .addEventListener function

I've been attempting to access the global object Vue.prototype.$firebase, which is declared in main.js. import Vue from "vue"; import App from "./App.vue"; import router from "./router"; import VueTailwind from "vue- ...

Error encountered when connecting to MongoDB: 'MongoServerSelectionError'

const uri = 'mongodb+srv:<username>//:<passwod>@chatapp-qrps3.azure.mongodb.net/test?retryWrites=true&w=majority' const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }) client.c ...

When coding on Github pages, the behavior of code blocks can vary depending on whether

I am interested in obtaining the offline version, which can be seen here: On the other hand, the online version has a different appearance: If you want to view the incorrect version, click on this direct link to visit the blog. A notable issue is the da ...

Leverage the retrieved JSON data from the database within an HTML template using the Play

Currently, I am facing a challenge with implementing a login feature in my project. I am struggling to figure out how to showcase the JSON string that is returned on the webpage. Below is a snippet of my code: Security.java: public Person webLogin(Perso ...

Ways to refine date results using JavaScript

Here is the JavaScript code I have: $(".datepicker").datepicker(); $(".datepicker-to").datepicker({ changeMonth: true, changeYear: true, maxDate: "0D" }); This code ensures that the date selected cannot be beyond the cur ...

Having issues with my code. Attempting to interact with a specific element on a webpage using its ID, but encountering difficulties

Is there a way to automatically click on an element on a webpage based on its ID in the HTML code? The ID for this particular button is "input-optionXXX" where XXX represents a 3-digit number ranging from 100 to 400. I need a python script that can scan ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

How to place a div within another div without using absolute positioning

I've been searching for a solution to this issue, but nothing seems to be working. I want the inner div to be positioned at the bottom of the outer div, with a 5px margin separating them. However, using absolute positioning disrupts the width and cent ...

Obtain a collection of keys that share identical values

In my JavaScript code, I have an array of objects structured like this: objArray = [ {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"}, {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"}, {"date":"07/23/2017 12:00:00 AM","cou ...

Hide the selection box when hovering over the Div

Looking for a quick solution. I want the option drop down to close when another div element is hovered over. First, open the drop down and hover over the red element on the right side. When hovering over the red element, I would like the drop down to clos ...