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

Creating a Website that Adapts to Different Browser Sizes: Tips and Tricks

I am currently working on a website that features a video background (mp4 file). However, I noticed that the video appears differently in Chrome, Explorer, and Firefox. In order to ensure compatibility across all browsers, I need to make some adjustments i ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapat ...

Styling in CSS to ensure scrollbar is constantly displayed without narrowing the container's width

Is it possible to have a vertically scrollable div with an always visible scrollbar without the scrollbar affecting the width of the elements inside? I attempted some CSS modifications, but the scrollbar still reduced the available width of the div. Is th ...

Leveraging HTML tables for input purposes

Just starting out with php, HTML, and mysql. Using HTML tables for the first time here. Created an HTML table filled with data from a MySQL table. Planning to use this table as a menu where users can click on a cell with a specific date. The clicked date ...

How can I make a div element match the height of an image and overflow without relying on

Here is the code that I am currently working with: https://codepen.io/allen-houng/pen/ExYKYdq Additionally, you can find a gist of the code snippet below: <div class="parent"> <div class="imageWrapper"> <img class="image" src="imageurl" ...

Implementing the expand and collapse functionality to the Discovery sidebar on the DSpace 4.2 xmlui platform

I recently began using DSpace and I am attempting to implement an expand/collapse feature in the Discovery sidebar of DSpace 4.2 xmlui using the Mirage theme. After finding some helpful jquery code, I attempted to add this functionality by placing the js f ...

The callback function fails to remove the JQuery row from the table

I am facing an issue with deleting a dynamically created row from a grid in my project. I use jQuery to send an Ajax request to the server to delete the corresponding data from the database. If the deletion is successful, I want to remove the row from th ...

Stop the bootstrap carousel at a specified screen size

Looking for a way to stop the bootstrap carousel from auto-playing on screen sizes below 640px. Despite trying various methods, I have yet to find a solution that works. This is my current approach: $(document).ready(function(){ if ($(window). ...

Splinter: Extracting XPATH text fragments that do not comprise distinct elements

How can I extract and store the text of the first, underlined, and last parts of the question using Splinter? Refer to the HTML below. I aim to assign the following values to variables: first_part = "Jingle bells, jingle bells, jingle all the" second_par ...

Manipulate DIV elements with jQuery by selecting them based on their class names and then

Is there a way to use jQuery to eliminate all DIVs on a webpage while preserving their content that have the following specific pattern? <div class="ExternalClass85AC900AB26A481DBDC8ADAE7A02F039">....</div> Please note that these DIVs adhere ...

Centralizing the Accordion header and expansion icon in React with Material-UI

I'm currently incorporating the Accordion feature from Material-UI library into my React project: My goal is to ensure that the accordion summary (header with "Accordion 1", "Accordion 2") is centered, and the expand icon (arrow) is also centered rig ...

Incorporate the column number class when using Masonry

Trying to put this into words is a bit tricky, but I'll give it a go. I'm curious if I can assign a class based on the column number within a Masonry layout. For instance, in a two-column layout, items in the left column would have a class of 1, ...

Prevent the colorpicker feature for the <input type="color"> element on Google Chrome

When using Google Chrome, the <input type="color"> element creates an input field with a color bar inside it. By default, it opens a colorpicker that may vary in appearance depending on the operating system (mine has a Windows theme). I have implemen ...

Events Unavailable for Viewing - Full Calendar - Database Error Encountered

I am currently developing a calendar application. While I have managed to successfully display the calendar and add events, I am facing an issue with displaying events on the monthly view. Here is a snippet of the HTML code being used: <head> &l ...

Comparing nestableSortable with the Nestable JavaScript library

I am in the process of developing a navigation menu editor that consists of multiple nested, sortable forms. My goal is to submit all the form data in one comprehensive JSON data blob. After researching, I have narrowed down my options to two libraries: n ...

Detecting the insertion of a DOM element with jQuery: locate a particular element

I am interested in learning how to detect when a SPECIFIC element is added to the DOM and then take action based on that. Initially, after the DOM has finished loading, there is a div(.myElement) that gets loaded much later: <div class="container"> ...

Error: Attempting to change a read-only property "value"

I am attempting to update the input value, but I keep receiving this error message: TypeError: "setting getter-only property "value" I have created a function in Angular to try and modify the value: modifyValue(searchCenter, centerId){ searchCenter.va ...

Running JavaScript function from AJAX response containing both HTML and JavaScript code

For my first time using AJAX to prevent page refresh upon form submission, everything works flawlessly. The data is received in HTML form and placed into the designated div. However, I am encountering an issue with one of the JavaScript functions responsib ...

Is there a lack of a feature for automatically shifting to the next input element in dynamically-created HTML?

I have a JavaScript function that is triggered when a user clicks a button: htmlstring = ''+ '<div class="input_holder">'+ '<div class="as_input_holder"><input tabindex="1" class="as_input form-control-sm ...

Utilizing Angular-cli and Karma for seamless integration with jQuery

I have scoured the internet and cannot seem to find a solution for my current dilemma, despite it being a widely known issue... Upon running ng test, I am faced with an empty Karma browser: Here is what my console displays: To incorporate jQuery, I foll ...