Tips for highlighting text in a textarea using jQuery or JavaScript

I'm intrigued by Facebook's functionality. They utilize textareas in their comments and status sections, but whenever I tag someone in a post, the selected text is highlighted with a light blue background within the textarea. As far as I know, this isn't traditionally possible with textareas, so what technique are they using? Does anyone have any insights or ideas on how they achieve this effect? I suspect there might be some sort of illusion or trickery involved, but I can't quite figure it out.

Answer №1

Utilizing a mixture of textarea and clever manipulation of div elements with CSS, the enchantment happens smoothly. Referred directly from Safari's Web Inspector:

<div class="inputContainer">
  <div class="uiMentionsInput" id="up84fa_5">
    <div class="highlighter" style="direction: ltr; text-align: left; ">
      <div style="width: 499px; ">
        <span class="highlighterContent"><b>Brandan Lennox</b> is the coolest.</span>
      </div>
    </div>

    <div class="uiTypeahead composerTypeahead mentionsTypeahead" id="up84fa_9" style="height: auto; ">
      <div class="wrap">
        <input type="hidden" autocomplete="off" class="hiddenInput">
        <div class="innerWrap">
          <textarea class="uiTextareaAutogrow input mentionsTextarea textInput" title="What's on your mind?" name="xhpc_message_text" placeholder="What's on your mind?" onfocus="return wait_for_load(this, event, function() {if (!this._has_control) {  new TextAreaControl(this).setAutogrow(true);  this._has_control = true; } return wait_for_load(this, event, function() {JSCC.get('j4f3584ff4f90d07867222385').init(JSCC.get('j4f3584ff4f90d07867222386'));;JSCC.get('j4f3584ff4f90d07867222386').init([&quot;buildBestAvailableNames&quot;,&quot;hoistFriends&quot;]);JSCC.get('j4f3584ff4f90d07867222383').init({&quot;max&quot;:10}, null, JSCC.get('j4f3584ff4f90d07867222385'));;;});});" autocomplete="off" style="height: 48px; direction: ltr; ">What's on your mind?</textarea>
        </div>
      </div>
    </div>
    <input type="hidden" autocomplete="off" class="mentionsHidden" name="xhpc_message" value="@[815490222:Brandan Lennox] is the coolest.">
  </div>
  <div class="attachmentMetaArea"></div>
</div>

The key components to note include:

  • The div.highlighter alongside its child element span.highlighterContent. Pay attention to how it formats a b element for the highlighted content.
  • The tangled onfocus handler within the actual textarea element. Somewhere in this block, a TextAreaControl object is established, seemingly creating an entity elsewhere in the DOM as the content within the textarea remains unaffected.
  • The
    input[type=hidden].mentionsHidden
    that transmits personalized data to the server to indicate the individuals mentioned.

While specifically tailored for Facebook, perhaps this insight can inspire creative possibilities for your own projects.

Answer №2

Instead of relying on a traditional textarea, this unique method generates HTML as you type, allowing for keyword highlighting and dynamic input repositioning. To witness this in action, inspect the element using Firebug to see the real-time effects.

Answer №3

After experimenting with the html5 demo, I've come up with a unique example that allows you to achieve the desired functionality. Feel free to take a look at it here: http://example.com/html5-demo. By simply instructing the browser to enable editing for a specific section and leveraging basic HTML features, this solution showcases the potential of html5 capabilities. While this approach may not be identical to how facebook implements similar functionalities, exploring html5's possibilities can be insightful as it represents the future of web development.

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

How can I fill the data array of arrays using an Angular Table component?

I am struggling to populate an Angular Table with data in the array of arrays format. Despite my efforts, the code I have written does not seem to work. Any suggestions for a solution would be greatly appreciated. Here is the data that I am trying to popu ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Tips for unselecting a card or button when hovering over another button or card in Angular 6

I currently have a page with multiple links such as project1, project2, and project3. Whenever a link is clicked, it directs to the dashboard page where all projects are displayed. The selected project should be highlighted with a color change. <a hre ...

How come modifications to a node package are not reflected in a React.js application?

After running "npm install" to install node modules, I made some changes to a module. The modifications are highlighted in a red rectangle. https://i.sstatic.net/KXdye.png The "find" command line tool only detected one file with that name. Next, I launc ...

Retrieve JSON-formatted HTML content to display as HTML within a React component

Wondering how to make the link actually render as a clickable hyperlink. Currently, when I read this line of text from my Json file, React displays the link as plain text rather than a clickable link. someData.json [{ "about": "John has a blog you ...

What is the best way to specify a function parameter as the `QUnit` type using TypeScript in conjunction with QUnit?

In my project, which is partially written in TypeScript and licensed under MIT, I am utilizing QUnit. I have some TypeScript functions that require QUnit as a parameter, and I would like to define their types based on its interface from the typings. For e ...

Is there a way to automatically animate an element each time it moves to a different position on the screen?

I am working on a Vue project and facing an issue where elements disappear on the page due to the use of v-if, causing the rest of the page to rearrange abruptly. I am looking for a way to make these changes happen smoothly. Each element on the page has a ...

Leveraging useEffect (or a comparable method) within a class component to create a loading screen

As a React newbie, I recently created a loading screen using useEffect in a functional component. Now, I'm trying to achieve the same using class components, but I'm facing some challenges. Here is the functional component that works perfectly: c ...

Using Node.js to leverage the async library for concurrently executing two tasks, then proceeding to start the final task after the first two have completed

Challenge Looking to run two tasks concurrently and then execute a third task after both are completed. I have been using the async library, which is functional but wondering if there is a more optimized approach. Tasks Task 1: readFileNames: Scans a di ...

How to properly declare an explicit injector when using the resolve parameter in $routeProvider?

$routeProvider resolve feature in AngularJS allows for injecting additional dependencies to the controller function. How can we combine this with explicit dependency injection declaration? Example: angular.module('myModule', []) .config(func ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Leverage the power of personalized SCSS styles in combination with Bootstrap-Vue, Webpack, and

I have been working on an application using VueJS with Bootstrap-Vue and I encountered a challenge while trying to import a SCSS file to customize the Bootstrap variables and add some custom styles. Here are the steps I have taken so far: Installed node ...

Navigating through a JSON document using jQuery

I've been attempting to iterate through a JSON string (located in a separate file named language.json) but I can't seem to make it work { "language": [ { "name": "English Languages", "values": ["English 1", "English 2", " ...

The font size appears significantly smaller than expected when using wkhtmltoimage to render

I am trying to convert text into an image, with a static layout and size while adjusting the font size based on the amount of text. I prefer using wkhtmltoimage 0.12.5 as it offers various CSS styling options. Currently, I am working on a Mac. Below is a ...

The contents table remains fixed in the top right corner as you scroll

I have developed an Angular app with a table-of-contents component that only displays two items. The code for the script is as follows: ts import { Component, OnInit } from '@angular/core'; import { pdfDefaultOptions } from 'ngx-extended-p ...

Is it possible to include og: meta information for Facebook after an Ajax load?

If you visit our website www.theshinebox.com, you'll notice that individual posts are loaded via AJAX. We want to make it possible to share or like these individual pages, but Facebook seems to be pulling information from the main page since it's ...

Highcharts - problem with chart width being fully rendered

I am currently using a Highcharts column chart and I am looking to make it a fully responsive chart with 100% width. The container for the chart is a simple <div> without any additional formatting. Upon document load, the chart remains at a fixed wid ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

I am seeing an unexpected '0' being added to my output when using the Ajax script in WordPress

I have developed a custom WordPress plugin that utilizes AJAX to refresh a div every 10 seconds. Although the AJAX GET request is functioning properly and displaying test as expected, it is also appending a 0 to the output in the div. (response) I'm ...