I'm trying to change the width of a div based on the content of the div:
Lets say initially the div has a width of 100px, I want it to remain at that width until the user has filled up 90px with text.
When this arrive the width of the div should be incremented by a fixed value. if the user writes even more (190px) the div will again have its width incremented.
I tried using the clientWidth of the div like this:
get style(): string {
if (!this.el) {
return `
width: 100px;
line-height: ${DEFAULT_HEIGHT}px;
max-height: inherit;
`;
}
let divWidth = 100;
const maxWidth = window.innerWidth - SCROLLBAR_WIDTH;
while (this.el.clientWidth > divWidth * 0.9 && divWidth < maxWidth) {
const width = width + 100
if (width > maxWidth) {
break;
}
divWidth = width;
}
return `
width: ${divWidth}px;
line-height: ${DEFAULT_HEIGHT}px;
max-height: inherit;
`;
}
but it does compare the width of the div with itself and not the content of the div.
Thanks in advance,
You can relate to this answer to get the content width: https://stackoverflow.com/a/47224153/12933115
My recommendation is that you use two nested DIVs like this:
<div id="container">
<div id="content"></div>
</div>
<input id="txtBox" />
The div#container would have a fixed size, whereas the div#content wouldn't.
#container {
width: 100px;
}
#content {
max-width: fit-content;
max-width: -moz-fit-content; /* For Mozilla Firefox */
}
Now, you detect the typing instead of the width. Then, you check the width of the inner DIV within the event listener.
const input = document.getElementById("txtBox");
input.addEventListener("input", () => {
// Check the width of the inner DIV (#content) here...
// If the width of the inner width exceeds your limit, then you change the width
// of the container DIV (#container).
});
The above was a general explanation. You'll figure out how to apply this according to your needs.