Editable span Option

One of my skills includes creating a dynamic contenteditable span within text that can expand and contract, as well as wrap around multiple lines without taking up the entire width:

div {
  width: 100px;
  background: #f00;
  padding: 5px;
}

span {
  border: 1px solid #000;
}
<div>
  <span contenteditable="true">Type Something</span>
</div>

I understand the difficulties and complexities associated with using contenteditable and prefer plain text. In order to achieve this, I am interested in using an <input type="text">. Is there a way to apply CSS/JS to make it function in a similar manner without having to simulate it programmatically with multiple input fields?

Explanation

A textarea is set to display: inline-block, however, setting it as inline does not truly replicate the behavior of an inline element like a span. Therefore, it does not serve as the alternative solution I am seeking.

Answer №1

When faced with a similar task in the past, I had to get creative and essentially create a custom textarea using div elements for each line, a span for the cursor, and some additional styling.

Here's the basic concept:

let $ = document.querySelector.bind(document);
let text = 'Type Something';
let cursor = text.length;

let updateDisplay = () => {
  $('#pre-text').textContent = text.substr(0, cursor);
  $('#post-text').textContent = text.substr(cursor);
};

document.addEventListener('keyup', e => {
  switch (e.key) {
    case 'ArrowLeft':
      cursor--;
      break;  
    case 'ArrowRight':
      cursor++;
      break;  
    case 'Backspace':
      text = text.substr(0, cursor - 1) + text.substr(cursor);
      cursor--;
      break;
    case 'Delete':
      text = text.substr(0, cursor) + text.substr(cursor + 1);
      break;
    default:
      if (e.key.length === 1) {
        text = text.substr(0, cursor) + e.key + text.substr(cursor);
        cursor++;
      }
  }
  updateDisplay();
});

updateDisplay();
div {
  width: 100px;
  border: 1px solid #f00;
  padding: 5px;
}

span#cursor {
  background: #000;
  width: 1px;
  height: 1em;
  display: inline-block;
}
<div>
  <span id="pre-text"></span>
  <span id="cursor"></span>
  <span id="post-text"></span>
</div>

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 troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

https://i.sstatic.net/q4x3m.png Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error ...

What is the best way to send a variable or query to a Python script from PHP using an Ajax request?

A Python script I have takes parameters or a SQL query from the PHP file, which I am running by calling an Ajax function. The PHP and Ajax call code has been added here. A variable "action" is created to check different cases. While I can execute action = ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

margin-top aligned to the bottom of two elements

Within this straightforward CSS snippet, my goal is to align the bottom of h1 with the bottom of p, without having h1 display below p. <div id="sqrs" style="width:200px; height:200px; border:1px solid BLACK;"> <p style="width:100px; height:100px; ...

Ensuring a URL is W3C compliant and functions properly in an Ajax request

I have a general function that retrieves URLs. This particular function is part of a plugin and returns URLs to various resources such as images and stylesheets within the plugin. GET parameters are used in these URLs for proper functionality. To ensure ...

Guide on designing a form for generating custom URLs

I have a form on my website that generates a URL, but it requires the user to wait until the entire page is loaded in order to function properly. I believe this is because I am using window.onload and should switch to using $(document).ready instead. How ...

A guide on navigating full images using CSS

I am searching for a code that will enable scrolling through entire images on my landing page. It is a bit challenging to explain, but it is similar to the style of scrolling on tesla.com. Each scroll of the mouse wheel moves down one complete image. Can ...

What is the best way to change data into an array using Java script?

In this code snippet, I am utilizing a loop to send data to an ajax function in JSON format: foreach($careers->getItems() as $item){ if($item->getDepartment()==$departmentID && $item->getLocation()==$location ...

Remove the div of the previous selection in jQuery and add the current selection by appending it, ensuring only one selection per row is allowed when

Here is a code snippet that includes buttons appending selections to the "cart" div upon clicking. The first script ensures only one selection per row when multiple buttons in the same row are clicked. In the second script, selections are appended to the ...

Colorbox scalePhotos function malfunctioning

The scalePhotos option in Colorbox does not seem to be working correctly for me. I have tried various methods to set it, including initializing Colorbox using the following code snippet right before the closing </body> tag in my HTML: jQuery('a ...

jQuery - Reveal one div while concealing another

I've been working on a script to toggle between two divs onClick - opening one while closing the other if it's already open. I'm fairly new to jQuery and Javascript, having mainly worked with HTML/CSS. Script I found: http://jsfiddle.net/J ...

Creating a Random Initial Index using jQuery

Is there a way to set a default variable as a random number within a specific range (such as between 1 and 100)? var defaults = { start_at_index: getRandomNumberInRange(1, 100), It's necessary for the default value not to be zero, but rather a rando ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

Invoking functions within a jQuery extension

I've come up with this code to define the instance of my plugin: $.fn.someplugin = function(opts) { $(document).on('click', '.option-1', function() { alert(1); }); }; To make my plugin work, I utilize code similar to this ...

Guide on scraping a site that employs Direct Web Remoting (DWR) for generating Javascript to interact with the HTML content of the page

When trying to crawl a specific website that appears to generate its content dynamically using DWR, I encountered a challenge. The source code of the page only reveals a minimal amount of HTML as a 'shell', without any useful links for crawling. ...

Access to the remote resource at https://localhost:8000/users/login has been blocked due to a Cross-Origin Request restriction imposed by the Same Origin Policy

Attempting to send a post message to the /users/signup endpoint results in the same error occurring repeatedly. Below is the code snippet from server.js: const https = require('https'); const fs = require('fs'); var path = require(&apos ...

Why is it considered bad practice to utilize cacheStorage outside of a serviceWorker?

According to the information provided on the https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage page: The CacheStorage interface serves as the storage for Cache objects, maintaining a directory of all named caches accessible to ServiceWorker, ...

Error in JSON data structure while transferring data from Jquery to PHP

Having some trouble with my first attempt at sending a JQuery request to an API I'm developing. My PHP code keeps reporting that the JSON is malformed. Interestingly, if I create a JSON array in PHP and send it through, everything works perfectly. Bu ...

Designing a website similar to sevenly.org using jquery: A step-by-step guide

My understanding of javascript and jquery is at a beginner level. I am interested in creating a design similar to Sevenly, where one page/div moves over another. I'm not sure where to begin with this. Any advice or ideas on how to implement this effec ...

HTML features various product displays across multiple pages

I am struggling with the terminology for my issues. I am currently working on an e-commerce project aimed at displaying products. My goal is to have only 30 products shown on each page, with product 31-60 displayed on page 2 and product 61-90 displayed on ...