The number of characters can be measured in a div element that is editable

Looking to create a character counter similar to Twitter in a contenteditable div. The goal is to restrict users to typing a maximum of 140 characters.

Using jQuery for character count and remaining display, but encountering an issue where the Enter key (new line) is not being counted as a character. Need to account for new lines in the character count.

Attempted using a textarea, but running into problems with specifying max-height to only show the scrollbar when exceeding this height. No limitations on lines or characters in the textarea.

DEMO: https://jsfiddle.net/oLomzakh/

In need of assistance to incorporate new line count in the character count. Can you help?

Answer №1

Instead of using $.text(), consider using $.html() to accurately detect line breaks including '\n' characters.

If you prefer not to use jQuery, you can also utilize the "this.innerText.length" property, though keep in mind it will include both '\r\n' for new lines instead of counting them as one character each.

To handle line breaks more efficiently, you can retrieve the $.html() content and replace <br> tags with a single character before calculating the final length.

Answer №2

Initially, functioning code:

maxCharacters = 140;

$('#char-count').text(maxCharacters);

$('#text-area').bind('input', function() {

    var count = $('#char-count');
    var characters = $(this).text().length;
    var newlines = $($(this).html()).length;

    if (!!newlines) newlines -= 1;

    characters += newlines;

    if (characters > (maxCharacters - 11)) {
        count.addClass('over');
    } else {
        count.removeClass('over');
    }
    count.text(maxCharacters - characters);

});

Next, an interpretation:

It appears that content-editable displays new lines using HTML (particularly in Webkit). Inserting a debugger; statement in the event handler, and examining the value of $(this).html() will show that:

https://i.sstatic.net/XMpXe.png

As evident from the presence of both div's and br's.

This is where

var newlines = $($(this).html()).length;
comes into play. It calculates the children of the element (including both div's and br's). Adjustment of newlines by -1 is necessary as there always remains a div or br post editing.

Including this with our $(this).text() value provides the accurate character count.

Answer №3

John's response is spot-on. If you also want to include white spaces and special characters in the character count, use the following code:

maxCharCount = 140;

$('#char-counter').text(maxCharCount);

$('#input-text').bind('input', function() {

    var charCount = $('#char-counter');
    var totalCharacters = $(this).text().length;

    if (totalCharacters > (maxCharCount - 11)) {
        charCount.addClass('over-limit');
    } else {
        charCount.removeClass('over-limit');
    }
    charCount.text(maxCharCount - totalCharacters);
});

I decided to eliminate these 3 lines of code:

var newLines = $($(this).html()).length;

if (!!newLines) newLines -= 1;

totalCharacters += newLines;

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

"Expo Securestore is encountering an issue where it is unable to store the user ID and token following authentication

I am currently working on securely storing the userId and token in SecureStore. I have successfully retrieved the token from SecureStore on the next screen, but for some reason, I am unable to see the userId. const doUserLogIn = async() => { try { ...

What steps can be taken to default to a Google web font when Helvetica is not available on the user's device?

Is there a way to have a font fall back to a specific one on Google Web Fonts (Open Sans) if the user does not have Helvetica installed? I'm looking for an efficient method where downloading the font is only necessary if needed. For example, I don&ap ...

"Embracing Progressive Enhancement through Node/Express routing and the innovative HIJAX Pattern. Exciting

There may be mixed reactions to this question, but I am curious about the compatibility of using progressive enhancement, specifically the HIJAX pattern (AJAX applied with P.E.), alongside Node routing middleware like Express. Is it feasible to incorporate ...

New to using JavaScript and JQuery, attempting to position a form underneath an image at a specific URL for the

Hello, I'm having difficulties placing a form below an image with a specific URL. As someone who is still learning JQuery, I am unsure of what mistake I might be making. Is there anyone who can help me figure out what's wrong here? <html> ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...

Select component experiencing issue with Material Ui label breaking

I've been working on implementing a select component, which is new to me. However, I'm encountering an issue with my MUI-select component. The label of the select element is no longer syncing properly with the select component itself as shown in ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Do the two types of updater functions for setState in React hold the same value?

Recently, I came across the concept of using updater functions for setState in React. After learning about this, I noticed it being implemented in two different ways. Imagine having a state object structured like this: interface State { readonly expand ...

Are you looking for a specialized jQuery Tree plugin with unique features and customization

Currently seeking a jQuery plugin with similar functionality to jQuery Multisortable. It should offer the following features: Split screen layout, with a tree structure menu on the left and content display on the right (similar to Windows Explorer). Abil ...

What is the method for retrieving posts based on a specific userID?

I am currently developing a project that requires displaying posts from a specific user when their name is clicked by either a guest or logged-in user. This involves passing the user's ID to the URL parameters in order to retrieve all the posts posted ...

There seems to be an issue with the server: Xt1.deprecate function is not defined

Currently, I am utilizing next.js version 13.4.12 with next-auth version 4.22.3 and prisma version 5.0.0, while also incorporating @next-auth/prisma-adapter version 1.0.7 in a TypeScript setup. Additionally, I have diligently followed all the necessary bo ...

Create a function that triggers a fade-out effect on one button when another button is clicked

Hello everyone! I'm still getting the hang of things around here so please be kind. I need some assistance with my weather app project. Specifically, I've created two buttons and I want to make it so that when one is clicked, the other fades to g ...

Using forEach Loop with Promise.all in Node.js

I am seeking a solution for a task where I need to read a directory, copy its contents, and create a new file within that same directory. function createFiles(countryCode) { fs.readdir('./app/data', (err, directories) => { if (err) { ...

What is the best method for saving and accessing a user-entered date using session storage?

https://i.sstatic.net/I8t3k.png function saveDateOfBirth( dob ) { sessionStorage.dateOfBirth = dob; } function getDateOfBirth() { document.getElementById("confirm_dob").textContent = sessionStorage.dateOfBirth; } function pr ...

Steps for implementing a conditional rendering in your codeHere is a

I've encountered an issue while attempting to implement conditional rendering. The error I'm getting is Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'types&apos ...

Ways to adjust the size of an HTML fieldset?

Is there a way to decrease the space between the paragraph and the border of this fieldset? I attempted to adjust the margins in the following manner: fieldset { margin: 1px; margin-top: 2px; border-top-right-radius: 1px; } <fieldset> < ...

Can anyone help me identify the issues in my PHP code?

My PHP code doesn't appear to be functioning correctly. Instead of displaying any errors, it simply shows a blank page. Can you identify what I might be doing incorrectly? <?php mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_ ...

What steps should be taken to address the issue when the .media$thumbnail.url cannot be located

Creating a custom widget for bloggers <script type="text/javascript"> function mycallback(jsonData) { for (var i = 0; i < jsonData.feed.entry.length; i++) { for (var j = 0; j < jsonData.feed.entry[i].link.length; j++) { ...

Utilizing Kendo UI DateTimePicker to transfer chosen date to moment.js

Currently, I am working with a Kendo UI DateTimePicker that provides the selected date in the following format: Thu Dec 15 2016 23:23:30 GMT-0500 My objective is to pass this date into moment.js for extracting the day information like so: var momentDate ...

PHP-generated table is designed with the attribute display:none

I'm encountering an unusual issue. My problem arises when I attempt to generate an HTML table through an SQL query using PHP. Here is an example of how I go about it: echo "<div id=\"table_div\">"; echo "<table id=\"ad_table& ...