0

I have been developing a chat room User Interface and I have a question.

In my UI I am using a div as my textbox and have a max message length of 500. There is a counter to show how many characters you have left, like '245/500'. On Google, this works fine but on safari, if you type one letter then delete it the counter goes from 1 to 4 and not 1 to 0. This also breaks my placeholder for the div.

Your help is much appreciated.

Here is some example code, clone it, then run it in Safari then try Google.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <title>HTML Stuff</title>

    <style>
        #text-div {
            width: 200px;
            padding: 10px;
            max-height: 50px;
            background-color: rgb(197, 226, 252);
            overflow-y: scroll;
            overflow-x: hidden;
        }
        
        #text-div:empty:before {
            content: attr(data-placeholder);
            color: rgb(102, 101, 101);
        }
        
        #counter {
            font-weight: bolder;
            font-size: 50px;
        }
    </style>

</head>

<body>
    <div id="text-div" contenteditable="true" data-placeholder="This is a Placeholder"></div>
    <div id="counter">0</div>
</body>

<script>
    var text = document.getElementById('text-div')
    var counter = document.getElementById('counter')

    $('#text-div').on('input', () => {
        counter.innerHTML = text.innerHTML.length
    })
</script>

</html>
MIMJA156
  • 107
  • 1
  • 8
  • Take a look at this link. Behavior for contenteditable divs is going to vary across different browsers. It might be better to use some kind of WYSIWYG editor, as they have much better comaptibility. Alternatively, you could see what innerHTML contains when you expect it to be empty - it might be whitespace that you can trim(), or an HTML element that will be harder to deal with. https://stackoverflow.com/questions/3455931/extracting-text-from-a-contenteditable-div – Joseph Mar 29 '21 at 21:18
  • If you aren't allowing HTML or other enhancements, using a styled textarea might be a better option. – imvain2 Mar 29 '21 at 22:30
  • `console.log(text.innerHTML)` – epascarello Apr 05 '21 at 20:41

1 Answers1

1

Using element.innerHTML will return the contents + the characters "&", "<", ">" as HTML entities "&amp;", "&lt;" and "&gt;" - MDN

Use element.innerText.length to get consistent results about the length of ONLY the contents!

var text = document.getElementById('text-div')
var counter = document.getElementById('counter')

$('#text-div').on('input', () => {
    counter.innerText = text.innerText.length - 1
})

Check the documentation!

pratiqdev
  • 51
  • 1
  • 6