Content changing programmatically does not reset the scrollHeight

As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the font size dynamically so that the added text fits within the div without exceeding its scrollHeight.

In certain scenarios, such as when the text is programmatically replaced or deleted by the user, the scrollHeight does not update accordingly. This poses a problem as the font size needs to be adjusted based on the actual content height of the div.

In the provided example, the clientHeight is 142 and the initial scrollHeight is 158. A loop is used to gradually reduce the font size until the scrollHeight matches the clientHeight. However, if a line of text is deleted, the scrollHeight remains unchanged at 142.

Below is the code snippet used to handle the font size adjustments:

    var textBox = document.getElementById('text');
    var current, min = 6, max = 14;
    current = textBox.style.fontSize.substr(0, textBox.style.fontSize.length - 2);
    current = parseInt(current);
    if (textBox.clientHeight < textBox.scrollHeight) {
        while (textBox.clientHeight < textBox.scrollHeight) {
            current--;
            if (current < min) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    } else if (textBox.clientHeight > textBox.scrollHeight) {
        while (textBox.clientHeight > textBox.scrollHeight) {
            current++;
            if (current > max) break;
            textBox.style.fontSize = '' + current + 'pt';
        }
    }

For reference, here is the HTML structure:

<div id="text" contenteditable="true"></div>

And the CSS styles applied to the div:

#text {
    position: relative;
    border: 1px solid blue;
    top: 180px;
    left: 31px;
    width: 300px;
    height: 132px;
    padding: 5px;
    font-family: 'mplantin';
    font-size: 14pt;
    font-weight: 200;
}

Answer №1

After trying different solutions, this finally resolved the problem:

element.style.height = "auto";

Answer №2

While facing a similar situation with an iframe, my approach may differ from what you're looking for in a chat window scenario. After conducting some tests, I came up with this workaround. Using the id `content' for the iframe, the following code snippet is executed within a JavaScript function triggered during page transitions:

var iframe=document.getElementById("content");
iframe.width=0;
iframe.height=0;
iframe.src="page.html";

The method of assigning `src' value and adjusting width and height to 0 immediately afterwards proved effective for accomplishing the desired outcome. While it might be possible to dynamically resize a text area in a similar manner, I encountered visual glitches along the way. To resolve this issue, I implemented timers to ensure seamless transitions between pages.

Answer №3

Both solutions provided by @nixahn and @jeff are successfully executing on my end in both Chrome and Firefox browsers.

iframe.style.height = "0"; // or set to "auto"
iframe.contentWindow.document.open();
iframe.contentWindow.document.write('<style>' + css + '</style>');
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

Answer №4

To solve the issue of auto resizing the element, I utilized a div with a fixed height. Following the setting of my inner HTML, I used this code snippet:

element.style.height = "auto";
 element.style.height = "400px";

This adjustment now accurately resets scrollHeight to provide the true height of the inner HTML content.

Answer №5

Dealing with the same problem here - a contenteditable div that refused to decrease its scrollHeight when lines were deleted.

Although the suggested solution didn't work for me, what did the trick was removing the "display: flex;" property from the parent div.

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

Image transformed by hovering effect

I've been attempting to add a hover effect to the images in my WordPress theme. The images are displayed in a grid format, created by the featured image on the posts. The grid layout is controlled within content.php <?php /** * controls main gri ...

A method to transfer a floating point number from Python to JavaScript without using cgi

Running an Apache server from a Raspberry Pi, I have a Python script that prints sensor input to the console. A PHP script then processes this output and controls a light based on the sensor reading before printing it again. Everything works fine when exec ...

Tips for utilizing the select feature within an ng-repeat loop while maintaining the selected value when fetching data from an API

I am currently facing an issue with using select inside ng-repeat. I am attempting to correctly map the value coming from my API to the select as the selected value. However, I seem to be missing something from my end. Can someone please help me identify a ...

Issue with Color in Line Chart of Flot Version 0.8.2

While working on Flot line charts and customizing their colors, I came across a strange issue. Once I set the first 3 colors, the plot started using the last color for all the remaining lines. This behavior was unexpected and not the norm. What adds to th ...

Toggle the display of dropdown 2 or dropdown 3 depending on the option chosen in dropdown 1

I am struggling with a form that contains 3 dropdowns: <select id="1" required> <option value="">Choose an option</option> <option value="1">Apple</option> <option value="2">Orange ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

Retrieving information from a PHP server using AJAX

Searching for a way to retrieve the posts created by users and load more posts upon user's request. Encountering an Unexpected end of JSON input error when initiating an ajax request in the console. Javascript $("#ajax_load_more").click(function ...

Having trouble fetching JSON data from a URL in my React Native project, the response is not as expected

getData() { return fetch("http://bitcfeedcms.rf.gd/script.php") .then(response => { console.log(response); response.json(); }) .then(responseJson => { this.setState({ data: responseJson }); }) .catch(error => { console.er ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

Sending data retrieved asynchronously to child components' props

Currently, I am developing an application that fetches an array of news items from a remote source and showcases them on a webpage. After successfully calling the endpoint using $.getJSON(), as indicated by console logs, I integrated this call into the pa ...

The target for ajaxSubmit is being duplicated instead of being replaced

I encountered a problem with the code below: $('#refresh').click(function () { alert($('.report-container').length); $('.report-container').each(function () { var accordian = this; var url = $(this) ...

Improving the pagination performance in AngularJS

I created an HTML template to showcase member details, along with adding pagination functionality to improve initial load time. Currently, I retrieve 15 members from the server at once and display them, allowing users to navigate through more members using ...

Adding color between lines in Three.js

I have two different sets of vertices. One set contains real vertices, and the other set contains the same vertices but with a y value of zero. I am trying to connect these vertices and fill them in but have not been successful so far. I have attempted to ...

Encountering a problem with AngularJS when attempting to access an array and display an alert message

While working with Angular, I encountered an issue in trying to access content stored within an array. Upon reviewing the code, console.log(JSON.stringify($scope.lineItems)) was returning [[]]. However, when inspecting or setting a breakpoint on this line ...

Error: Unable to assign a value to the statusCode property because it

During the development of my application backend, I encountered an error while working on the user login route. When testing the route using Postman, I received the following error message: UnhandledPromiseRejectionWarning: TypeError: Cannot set propert ...

Adding the Authorization header in an Ajax request within ExtJS can be easily done by including the

I've been struggling to upload a file using ExtJS and web API. The issue I'm facing is that when trying to send an authorization header to the server, it always returns as null. I even attempted to include the header in the XHR request within the ...

JQuery - Select element by clicking outside

I'm trying to figure out how to hide an element when clicking outside of it. Found a solution at: https://css-tricks.com/dangers-stopping-event-propagation/ $(document).on('click', function(event) { if (!$(event.target).closest('#m ...

Attempting to program a bot to navigate in a random pattern across a two-dimensional xz plane using Threejs

My journey began with the code below, which initiates a block moving in a straight line: const bot_geometry = new THREE.BoxGeometry(1,1,1); const bot_material = new THREE.MeshBasicMaterial( {color: 0x7777ff, wireframe: false} ); const bot = new THREE.Me ...

What methods can I use in Mocha with Sinon for testing multiple callbacks?

My code involves a function with asynchronous operations and multiple callbacks var f = (cb1, cb2) => { return new Promise((resolve, reject) => { /* ... */ }); }; During testing, I wanted to use sinon to create spies var cb1Spy = sinon.spy(); va ...

The organizational chart function was functioning properly on the local environment, however, it failed to work after deployment, resulting in the error message "jQuery(

Currently, I am in the process of creating an organizational chart using the Angular library called orgchart. The code I have developed works fine on my local machine, but when we deploy it onto our nginx server, we encounter an error related to jQuery. T ...