Display the current position of the caret in a field that cannot be edited

Can a virtual caret be displayed between two letter boundaries in HTML/CSS/JavaScript, for example in a regular div without using contenteditable=true?

Imagine having the following:

<div>Hello world</div>

If I were to click between the "w" and "o" in "world", is there a way to show a virtual caret so it appears like this:

Hello w][orld

Answer №1

Here is the code snippet in HTML:

<div id="content">Lorem ipsum dolor sit amet</div>

And here is the corresponding Javascript code:

var text = document.getElementById("content").innerHTML;
document.getElementById("content").onclick = function() {
    var cursorPosition = window.getSelection().focusOffset;
    document.getElementById("content").innerHTML = text.substr(0, cursorPosition) + "][" + text.substr(cursorPosition);
}

Answer №2

There are two ways to obtain a character (and its corresponding position) within the text of an element under the mouse cursor. The first method involves enclosing each character in a <span> or another element, and adding a click event handler to the <span> element. The second method utilizes the functionalities of the Range object, which is supported only by pure JavaScript. Personally, I prefer the first approach due to its efficiency. Using the Range method necessitates looping each time a click occurs, potentially leading to performance issues when dealing with large texts. For creating a virtual caret, you can generate an inline-block element and visually represent the caret using techniques like borders with linear-gradient backgrounds or even a transparent PNG image. By adjusting margins (both negative for left and right), you can bring text closer together on both sides. Below is the detailed code:

HTML:

<div class='inter-letters'>Click on one of the characters ...</div>

CSS:

.v-caret {
  width:.5em;
  height:1em;
  border-top:1px solid currentColor;
  border-bottom:1px solid currentColor;
  background:linear-gradient(to right, transparent .23em, currentColor .25em, transparent .27em);
  display:inline-block;    
  vertical-align:middle;    
  margin:0 -.2em;
  display:none;
}
.inter-letters {
  font-size:30px;
  color:green;
}    

JS:

$('.inter-letters').on('click','span.letter', function(){
  virtualCaret.css('display','inline-block');
  $(this).after(virtualCaret);
}).html(function(i,oldhtml){
          return oldhtml.replace(/./g,"<span class='letter'>$&</span>");
        });
var virtualCaret = $('<div>').addClass('v-caret').appendTo('.inter-letters');
//clicking outside the div should hide the virtual caret
$(document).click(function(e){    
  if(!$('.inter-letters').has(e.target).length) {        
     virtualCaret.css('display','none');
  }    
});

Demo.

Answer №3

If you utilize a monospace font, it is possible to create a line at a specific location.

Assuming each character is 7 pixels wide

$('#div').click(function (e) { //Calculate mouse position
    var posX = $(this).offset().left; // get click offset
    var caretX = Math.floor(posX/7); // calculate whole characters
    caretX += posX%7 > 7/2 ? 1 : 0; // decide which way to shift if not clicked exactly between two characters

    // Now use caretX as X position for a caretline element to be placed absolutely
});
  • Using jQuery how to get click coordinates on the target element

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

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

Display a custom error message containing a string in an Angular error alert

How can I extract a specific string from an error message? I'm trying to retrieve the phrase "Bad Request" from this particular error message "400 - Bad Request URL: put: Message: Http failure response for : 400 Bad Request Details: "Bad Request ...

What is the reason that the CSS3 property name 'filter' is not recognized in Windows 8 applications?

I'm in the process of adapting my own codepen for a Windows 8 desktop app. Everything runs smoothly on Codepen, with the exception of some CSS adjustments from -webkit- to -ms-. However, I encountered an issue regarding this specific line in the CSS s ...

Preventing bots and spiders from infiltrating the ad network. Stepping up efforts to block unwanted traffic

We are facing a constant battle against bots and spiders with our in-house ad system, striving for 100% valid impressions. To achieve this goal, I conduct experiments on a specific ad zone that is only displayed on one page of our site. By comparing the G ...

Basic email subscriber form using PHP and HTML

Seeking assistance in creating a basic subscriber email form where users can input their email addresses. Upon submission, I would receive an email notification indicating a new subscription and the client would be informed that we will get in touch with t ...

The Vue plugin encountered an issue with an error message stating "Uncaught SyntaxError: Unexpected token

I'm excited to dive into using vue for my upcoming project. I decided to incorporate Hooper, an image carousel, and went ahead to install it using npm install hooper. To implement it in my script file, I included the following code: import { Hooper ...

Utilizing Javascript in Spotfire for enhanced functionality

Currently, I have a dropdown menu with two options ("START" & "END"). Depending on the selected value from this dropdown, I want to display a specific DIV element. I attempted to use the code below, but unfortunately, it is not functioning as expected ...

Trouble with CSS submenus: Are your lists not appearing as they should? Potential style override

I am encountering an issue with my dropdown mega menu. I have two sets of list items that should be displayed vertically side by side with bullet points in the dropdown, but only one list is appearing despite coding for both. Additionally, the list elemen ...

Searching for related values in a nested array of objects using JavaScript: A guide

My goal for this project is to thoroughly examine the path along with all nested elements within the Items and assign them to the details variable. However, due to the limitations of the function inside the useEffect, I am unable to check nested items eff ...

Generate a text input field within a dropdown menu

Below is an example of my basic HTML code for a drop-down list: <span id="Div_List"> <label for="Gender">For:</label> <select name="Gender" id="Sex"> <option value="1">1000mtr</option> <option val ...

What could be the reason why both the add and remove functions are unable to work simultaneously within a JavaScript function?

Hi there! I recently started diving into JavaScript and encountered a little hiccup. I've been working on a dice game where images change randomly whenever a button is clicked. The images transition from one to another, but I wanted to add a rolling ...

JavaScript: Adjust DIV Width Based on Window Height

Is there a way to make the width of a div equal to the height of the window in jquery? I attempted this method: <script type="text/javascript"> $(".rt-container").style.width = $(window).height(); </script> Unfortunately, it did not work. I ...

Enhance your image viewing experience with a React component that smoothly zooms in on images without distorting their dimensions, all with

After searching extensively for a solution, I have been unable to find one that works. My current setup involves using React with Bootstrap. I am in need of a stateless functional component that can take an image path as input and return an img element. Th ...

Adjust the contents of a DIV depending on which Toggle button is selected

When a user clicks on either "Twin Bed" or "King Bed", the content inside the "demand-message" should change to either "high demand" or "Only ??? rooms left". The ID will remain the same for both buttons due to existing logic. However, the message display ...

How can I extract a specific portion of HTML content using C#?

I am working on a page where I need to extract a substring using the following code: static string GetBetween(string message, string start, string end) { int startIndex = message.IndexOf(start) + start.Length; int stopIndex ...

What makes Safari for Windows stand out when it comes to AJAX?

What sets Safari for Windows apart when it comes to handling AJAX requests? Moreover, are there any potential issues or challenges I should be aware of? ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Is it possible for me to insert a hyperlink that will show a PDF in a web browser without triggering a download?

I am looking for a way to allow visitors to my website to easily access and view a PDF directly in their browser by clicking on a specific URL or button. I want the PDF to be displayed within the browser itself, rather than prompting a download. Any guidan ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...