Guide for using JavaScript to obtain the current line position within a contenteditable div during a keypress event

I am in the process of developing a customized editor using a contenteditable div. I require a javascript code that can determine the line position of the current caret position during a keypress event. It should be able to adapt when new lines are added or removed.

Here is the format of my contenteditable div

<div contenteditable="true" id="editor">
  <b>Heading</b>
  <br/>
  Line 1
  <br/>
  Line 2
  <br/>
  Line 3
  <br/>
  Line 4
  <br/>
  Line 5
</div>

To view a demonstration, please visit this fiddle:

Answer №1

To display code, you should utilize a <pre> element.

HTML Code

<pre  contenteditable="true" id="editor">
line 1
line 2
line 3
line 4
line 5</pre>

<input id="addBtn" type="button" value="Add Line"/> 

JavaScript Code

$('#editor').on("mouseup", function getPos() {
    var sel = document.getSelection(),
        nd = sel.anchorNode,
        text = nd.textContent.slice(0, sel.focusOffset);

    var lineNum=text.split("\n").length;
    alert(lineNum);
});

$('#addBtn').click(function(){
   var str = "new line";
   elem = document.getElementById("editor");
   elem.innerHTML =  elem.innerHTML +"\n" + str;        
});

I have made changes in my jsfiddle, opting for a pre tag instead of using <br/> for line breaks. Check it out here

Answer №2

It's unclear what exactly you're aiming to accomplish, but I may have a solution. In a previous project of mine, I encountered a similar scenario where I needed to extract text from input boxes. My suggestion is to assign unique IDs to each paragraph, line, or input box and then attach an event to the div containing these elements. By doing so, you'll have the freedom to execute various actions.

For instance: You don't necessarily need to target the body element; you can simply apply the event listener to your specific div.

document.body.addEventListener("foo_event", get_target, false);

<p id="someid">Insert interesting content here—this could be text, an input field, or anything else.
Assign IDs to all lines for easy referencing and consider adding classes for styling purposes.</p>

function get_target(e){
 //Something has triggered the event, let's respond accordingly

    if ("someid" === e.target.id ) {
         //Execute code specific to this paragraph or element

/* Ideally, it's best practice to implement an algorithm for ID testing rather than relying on multiple if statements */
     }

}

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

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...

Is there a way to divide v-progress linear into 4 pieces in Vuejs, or are there alternative design options for achieving this in Vuetify 2?

I have set up a table in Vuetify 2 with a v-progress-linear component to monitor the user's remaining time. Initially, my implementation was simple like this. https://i.sstatic.net/x373G.png However, we decided to split it into 4 sections for better ...

Revamping a design using Mustache js

I've successfully implemented mustache js to render a template using data from an API, but now I face a challenge in updating the same template at a later time. Within my template, there is a list structured like this: template.html <div id="temp ...

Is there a method to achieve greater accuracy when dividing a large number?

My requirement involves operating on Big Numbers, and I need the results to maintain precision, as demonstrated below: const BN = require('bn.js'); var a = 11060622312717714974 var b = 1570481433500000000000; console.log(a/b); //0.00704282271460 ...

Attach functions to elements added dynamically

I've been struggling with trying to attach functions to newly added elements using jQuery. Despite experimenting with various online examples, I haven't been able to get anything to work properly. My setup involves a form with an ID and a button. ...

Obtain ID and Class details from an HTML webpage using VBA

A few months back, I developed a program in Excel VBA to extract specific information about the prices of my game collection from an HTML page. Initially, it worked perfectly fine but suddenly stopped functioning about a month ago. I'm struggling to f ...

What is the best way to showcase content based on data hooks?

I am facing an issue where my form is not displaying the desired entry as expected from my code. The goal is to show a message indicating that the phone number entered by the user is already in use and display it as invalid. I have implemented logic to ch ...

Unable to retrieve the length of HTMLCollection

I've been having an issue with accessing all the dynamically created list elements (<li>) on my page using getElementsByTagName. The console keeps showing that the length of my li array is 0. Despite going through documentation and examples rel ...

Sending an Ajax request to the MVC Controller results in a response of "NOT FOUND"

Trying to use AJAX to call a MVC Controller action with certain parameters has been successful in the past within this application. However, for some reason, THIS SPECIFIC ONE is not functioning properly. function deleteDetail(button, tab) { var i ...

What is the meaning of "bootstrapping" as it relates to Angular 2?

I found a question that is similar to mine, but I think my case (with version 2) has enough differences to warrant a new discussion. I'm curious about the specific purpose of calling bootstrap() in an Angular 2 application. Can someone explain it to ...

Implementing AJAX mysqli interaction in PHP following the MVC design pattern

Today I'm encountering yet another AJAX-related error. I am in the process of developing a user registration system using AJAX and PHP, following MVC architecture. Previously, I successfully built a login system without AJAX that functions flawlessl ...

Tips for accessing req.fields variables while utilizing Express-Formidable

For some reason, I am encountering difficulties when trying to access variables parsed within req.fields using Express-Formidable. Upon executing a console.log() of req.fields, the output is as follows: { 'registration[username]': '1', ...

Guide to capturing and playing audio on iOS6 with HTML5

Our team is currently working on a web application using HTML5 and Javascript. We are facing a challenge with implementing voice recording functionality, as the Wami Api we tried is not compatible with iPad due to its use of flash for recording. Could yo ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

Chrome compatibility problem with scroll spy feature in Bootstrap 3

Having trouble with scroll spy for boosters using the body method " data-spy="scroll". It seems to be working for some browsers like Edge and Google Chrome, but after multiple attempts, it still doesn't work for me. Even after asking friends to test i ...

What is the best way to interpret a JSON object?

Trying to extract data from a PHP web-service using JavaScript, an error occurred in my project while parsing JSON. The PHP web service code is as follows: <?php header("Content-Type:application/json"); try { if(!empty($_POST['mobile_number& ...

Converting SQL database tables into MVC webpages using JavaScript

Currently, I am working on populating an MVC webpage by utilizing a Controller and a View using C#, HTML, and Javascript exclusively. It is crucial that I avoid using a model or PHP due to the existing format in use. Thus far, all the data has been succes ...

Creating a Basic JQuery Dialog Box

Issue with jQuery Trigger <script type="text/javascript" src="simpledialog.js"></script> <link href="simpledialog.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> $(document).ready(function () { $('.s ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Using NodeJS to integrate WebRTC into JavaScript applications

I am facing a challenge with my JavaScript files that I need to use for creating a WebRTC application. Unfortunately, my hosting platform does not support Node.js. I'm wondering if it's possible to modify these JS files to work without Node.js. C ...