I ran a test on the code you provided and found that the scrollWidth and scrollHeight values were much larger than the actual text size.
To accurately measure the size of the text, one helpful method is to create a span element with the same font styling as the text area, then copy the textarea's value into it before appending the span to the document. By using getBoundingRect(), you can determine the dimensions of the span and, subsequently, the text within your textarea.
IMPORTANT: I decided to change the id of the parent div because it was identical to the textarea's id. It's crucial for ids to be unique, as having two elements with the same id can potentially cause JavaScript issues. Here's the updated blur function along with the jsfiddle link for reference: https://jsfiddle.net/yog8kvx7/7/.
$('.notesArea').blur(function (event)
{
var content = $(this).val().trim();
var element = document.getElementById(event.target.id);
// Create span to calculate width of text
var span = document.createElement('span');
// Set position to absolute and make it hidden
// so it doesn't affect the position of any other elements
span.style.position = 'absolute';
span.style.visibility = 'hidden';
// Only set to whitespace to pre if there's content
// "pre" preserves whitespace, including newlines
if (element.value.length > 0)
span.style.whiteSpace = 'pre-wrap';
// Copy over font styling
var fontStyle = window.getComputedStyle(element);
span.style.display = 'inline-block';
span.style.padding = fontStyle.padding;
span.style.fontFamily = fontStyle.fontFamily;
span.style.fontSize = fontStyle.fontSize;
span.style.fontWeight = fontStyle.fontWeight;
span.style.lineHeight = fontStyle.lineHeight;
span.innerHTML = element.value;
// Add to document and determine width
document.body.appendChild(span);
var rect = span.getBoundingClientRect();
var width = rect.width;
var height = rect.height;
// Remove span from document
span.parentNode.removeChild(span);
$(this).animate({
width: width,
height: height
}, 100);
});
If you need to consider the sizing handle to prevent it from covering the text, simply add an offset to the width accordingly.