Ways to alter the appearance of individual characters in the text input

My latest project involves dynamically changing the CSS styles of each individual character in a given text input. For example, if the user types "Stack" into the input field, I want the 'S' to appear in red, 't' in blue, 'a' in green, and so on.

var myModel = {
name: "Mayur",
};

var myViewModel = new Vue({
el: '#my_view',
data: myModel
});
span{
color:green;
font-weight:600;
font-size:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>

<div id="my_view">
  <label for="name">Enter name:</label>
  <input type="text" v-model="name" id="name" name="name" />
  <p>Welcome, <span>{{ name | uppercase }}</span></p>
</div>

Answer №1

Although I have limited experience with Vue and its internal events and processes, I have created a small prototype using pure JavaScript:

document.querySelector('button').onclick = function (){
    let span = document.querySelector('span.letters'),
        text = span.textContent;
    span.innerHTML = '';
    Array.from(text).map(function(l){
        let color = document.createElement('span');
        color.innerHTML = l;
        color.style.color = 'rgb(' +
            randInterval(0, 255) + ',' +
            randInterval(0, 255) + ',' +
            randInterval(0, 255) + ')';
        span.appendChild(color);
    });
}

function randInterval(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}
<div><span class="letters">STACK</span></div>

<button>Random colors</button>

I intentionally encapsulated the function that randomizes the rgb() values into a separate function for easy manipulation (ensuring truly random colors). To create darker colors, you can decrease the max values. For lighter colors, increase the min values.

Answer №2

Website Development:

<div>Enter text here, then click below the white space to see magic happen!</div>
<input type="hidden" id="hidden">

Javascript Magic:

$("div").prop("contentEditable", true).blur(function(){
    var chars = $(this).text().split("");
    $("#hidden").val($(this).text());
    this.innerHTML = "";
    $.each(chars, function(){
        $("<span>").text(this).css({
            color: "#"+(Math.random()*16777215|0).toString(16)
        }).appendTo("div");
    });
});

Cool Styling with CSS:

div{
    border: 1px solid black;
    width: 400px;
    height: 20px;
    padding: 2px 3px;
    overflow: hidden;
}

Check out the implementation at http://jsfiddle.net/DerekL/Y8ySy/ for a live demo!

The code provided will randomly color characters, but you can easily customize it or keep them running randomly as is.

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

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

Conceal the initial element featuring an image

Given that the post-body includes various elements, such as links and divs, I am interested in concealing only the first child element that contains an image. <div class="post-body"> <div class="separator"><img/></div> </div&g ...

What could be the reason my Virtual Mongoose categories aren't appearing?

Here is the description of my post model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PostSchema = new Schema({ text: String, image: String, author: { type: Schema.Types.ObjectId, ref: 'user&ap ...

Divs are the preferred placeholders over inputs and textareas

For the past few weeks, I have been trying to tackle a problem with creating placeholders that guide users on where to type. My goal is to make these placeholders disappear when users start typing and reappear if the div is empty again. All my attempts so ...

The function Amplify.configure does not exist

Currently attempting to utilize AWS Amplify with S3 Storage, following the steps outlined in this tutorial for manual setup. I have created a file named amplify-test.js, and here is its content: // import Amplify from 'aws-amplify'; var Amplify ...

Displaying API response array object in React application

Currently, I am attempting to retrieve information from an API, parse the response content, and then display it in a loop. However, I have encountered a warning message: webpackHotDevClient.js:138 ./src/App.js Line 20: Expected an assignment or function ...

Passing the title of a page as data to a component in Next.js

I am currently working on setting a custom title for each page within my next.js project. Here is an example of a simple Layout: const MainLayout = props => { return ( <Layout style={{ minHeight: "100vh" }}> <Head> < ...

A guide on displaying a JSON object using the ng-repeat directive

Looking to create a dynamic treeview menu with angularJS? Wondering how to achieve the desired results using a controller ($scope.results) and JSON data? Check out the code snippet below for an example of how to structure your treeview: <ul> < ...

I am having trouble sending the text of a selected list item from a dropdown menu to the controller from the view in MVC4. The controller is receiving a null value. Can someone please

This is my code snippet for creating a dropdown menu to select classes: <div class="dropdown"> <button class="btn btn-danger btn-lg dropdown-toggle" type="button"id="menu1" data-toggle="dropdown">Go To Class<span class="caret"></ ...

When applying styles in Polymer, it's important to take into account the width and height

Having trouble setting the width of elements within container elements in Polymer. Here's a simple example that illustrates the issue: <!doctype html> <html> <head> <base href="https://polygit.org/polymer+:master/webcomponent ...

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

Trouble arises when attempting to bind a JavaScript event with an innerHTML DOM element

I am currently dealing with a complex issue on how to bind a JavaScript event to an innerHTML DOM element. The scenario involves having a div with an input checkbox inside it, along with some pre-existing JavaScript event bound to that checkbox. Additional ...

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

The usage of event.returnValue has been phased out. It is recommended to utilize the standard event.preventDefault()

Here's the code snippet I'm working with: <script> $(document).ready(function () { $("#changeResumeStatus").click(function () { $.get("{% url 'main:changeResumeStatus' %}", function (data) { if (data[&apos ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Encountering a Next.js prerendering issue when using getStaticPaths

I am currently developing a Next.js application. Here is the structure of my files: cpanearme -components -listitem.js -pages -home -index.js -firm -[id].js Below is the code for a list item that redirects to the dynamic rout ...

Steps for implementing a dropdown select within a header of a Vuetify table

I'm working on a component that renders a Vuetify table, and it gets its header props from an interface like this: export const tableData: TableData = { headers: { text: 'Name', value: 'name', ...

Identify matching values in objects and dynamically update them with a custom value

I have an array structured like this: var array = [ { dates: "2020-12-25", class: "first" }, { dates: "2020-12-26", class: "last" }, { dates: "2021-06-11", class: "first" }, ...