Modify the background color of each word within the search bar

I've been attempting to colorize each word using jQuery and give them a colored background. I came across a solution, but it only seems to work for the HTML content, not the input field in the search bar. Below is an example of what I found:

HTML

Some content
<div>Another content 
    <input id="search" type="text" value="dsfdsfdsf sdf dsfsdfsfs">
</div>
<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ac turpis
</p>
Content in body

jQuery

//The main point here is that you need to replace only the contents of the text node, not all the HTML parts

var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray'];
var lastC;

jQuery('*').contents().each(function () {
    // Not a text node or there is no content to replace
    if (this.nodeType != 3 || !this.nodeValue.trim()) {
        return;
    }

    // Replace the value of the text node
    $(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
        var c = colours[Math.floor(Math.random() * colours.length)];
        while (c == lastC) {
            var c = colours[Math.floor(Math.random() * colours.length)];
        }
        lastC = c;
        return '<span style="background-color: '+c+';">' + part.split("").join("") + '</span>'
    }))
});

I attempted to change jQuery('*') to jQuery('#search'), but it didn't work.

Live example https://jsfiddle.net/7hs9mgLp/2/

What should I do to fix this issue?

Answer №1

Interestingly, this function does not work with a text input element because it wraps the content in a span element rather than the value of the element.

However, I have come up with a solution to make it functional with your code by applying a random color to the background of the input element.

Check it out here

This is the JavaScript code provided:

// The key point here is to only replace the contents of the text node, not all the HTML elements

var colours = ['red', 'green', 'blue', 'cyan', 'magenta', 'yellow', 'gray'];
var lastC;

jQuery('*').contents().each(function () {
    // If not a text node or there is no content to replace
     // Here's the part that has been modified. It checks what type of element is being retrieved
     if ( $(this).is( "input" ) ) {
        color = colours[Math.floor(Math.random() * colours.length)];
        $(this).css('background-color',color);
     }
    else{
      if (this.nodeType != 3 || !this.nodeValue.trim()) {
          return;
      }

      // Replace the value of the text node
      $(this).replaceWith(this.nodeValue.replace(/\w+/g, function (part) {
          var c = colours[Math.floor(Math.random() * colours.length)];
          while (c == lastC) {
              var c = colours[Math.floor(Math.random() * colours.length)];
          }
          lastC = c;
          return '<span style="background-color: '+c+';">' + part.split("").join("") + '</span>'
      }));
    }
});

EDIT

Adding color to each word in the input can be a bit tricky and there might not be a "clean" way to achieve it.

Nonetheless, here's a suggestion I have for this aspect:

View the updated fiddle here

I made some changes to the HTML structure to accomplish this as I couldn't think of another method. I hope this helps.

Here's the updated JavaScript section:

if ( $(this).is( "input" ) ) {
  val = $(this).val().split(" ");
  $( val ).each(function(i,v ) {
    color = colours[Math.floor(Math.random() * colours.length)];
    $("label").append("<span class='absolute' style='background-color: "+color+"; '>"+v+"</span>");
    $('#search').css('position','relative');
    $(this).val('');
    $('label').css({'position' : 'absolute', 'left' : '2px', 'top' : '2px' });
  });
}

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

Experience a seamless front/back DIV transition with a mouseover effect similar to the ones on USAT

Recently, I was tasked with creating a mouseover transition effect for a div similar to the one used on USAToday's website. The structure of the boxes on the site includes: <div class="asset"> <div class="front">'image and some t ...

Modify the c3 axis labels using CSS

I've been using the c3 package in R, which serves as a wrapper for the C3 javascript charting library created by Masayuki Tanaka. One issue I encountered is that my c3 chart was cutting off the last date on the x-axis. After inspecting it in Chrome I ...

Ajax is malfunctioning and failing to fulfill my needs

I cannot get Ajax to submit no matter what. I've been struggling for hours... script: <script> $(document).ready( $("#submit").click(function(e) { e.preventDefault(); $.ajax({ url: "https://maps.googleapis.com/maps/ ...

Unable to select the option in select2

While attempting to implement select2 jQuery, I encountered an issue where the data retrieved from the database was displayed properly as I typed in the input field and scrolled through the options, but I was unable to click on any of the displayed data. I ...

Obtaining data with jQuery.Ajax technology

I am attempting to retrieve real-time data from a different URL and display it in a text field every second without refreshing the entire page. The content of the URL is constantly changing, so I want the field to update accordingly. However, despite my ef ...

Bring a div box to life using AngularJS

Struggling to animate a div-Box in AngularJS? Despite trying multiple examples, the animation just won't cooperate. I'm aiming to implement a feature where clicking on a button triggers a transition animation to display the search form. I under ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Background image for input button in Internet Explorer 6

Can you create a custom background image for the input type="button" in Internet Explorer 6? ...

Exploring the process of setting a background image within a div tag

My goal was to design a clickable box that would redirect users to "#". I initially thought about using area maps within div or p tags, but unfortunately that wouldn't work. Does anyone have any suggestions for alternative solutions? ...

What is the best method for converting a variable with HTML content into a printable string?

In an attempt to display user-entered data from a text box to an HTML div, there seems to be an issue when the data contains HTML content. Instead of displaying the content as a string, it shows it as HTML elements. For example: let text = "<h1>Worl ...

Enter the value into the text area using ajax technology

My goal is to dynamically populate one textbox based on the value entered into another textbox. For example, if I input "pencil" in try1 field, the value "A00003" should automatically appear in the try2 field. I have managed to display the value in an aler ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

The Ajax script is failing to retrieve search results

I am encountering an issue with my normal AJAX search functionality in which I need to retrieve data from a database when the form is submitted. The problem arises when trying to filter data between two specific dates using separate pages, it works fine bu ...

Tips for retrieving the count from HTML using JavaScript:

I need to determine the count of list items in an unordered list within dir-pagination-controls. How can I achieve this using JavaScript? <dir-pagination-controls min-size="1" direction-links="true" boundary-links="true" class="pull-right ng-isolate- ...

Searching for a method to locate and substitute a specific HTML string using the `sed` command in the macOS Catalina terminal

I am attempting to modify the following html code: <svg xmlns="http://www.w3.org/2000/svg" width="20" viewBox="0 0 256 256"> to this updated version: <svg xmlns="http://www.w3.org/2000/svg" width="30&q ...

Limit the radio button to being clickable

Ugh, I'm really struggling with this. I want to create a quiz where only the radio button is clickable, not the text itself. Can anyone help me figure out how to do this? I have two codes below that I don't quite understand. I'll include th ...

Deactivating the ajax function is one of the key features of the Framework

I recently attempted to transition my app from plain HTML to framework 7, and while most things were running smoothly, I ran into a roadblock when it came to ajax requests. They simply wouldn't execute, resulting in an error message. Uncaught TypeErro ...

javascript unable to change the text in the textarea

My application takes user input from a textarea element, calls an API to retrieve values, and then compares those values against a list of known "badwords." If a match is found, the word is highlighted in red to indicate it is spelled incorrectly. The pro ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...

Conceal anchor links using jQuery by targeting their title attribute

Looking at the html below <li class="static"> <a title="blog" class="static menu-item" href="http://google.com">Blog</a> </li> <li class="static"> <a title="profile" class="static menu-item" href="http://profile.com"> ...