Animate text area to fit the contents of the text area - javascript

I want to resize the textarea to fit the contents of the text area.
I am currently using the following code to do that:
var element = document.getElementById(event.target.id);
var content = $(this).val().trim();
if (content == "") {
$(this).animate({
width: element.scrollWidth,
height: element.scrollHeight
}, 100);
}
When I enter nothing. I expect the textarea to become smaller in size and eventually disappear.
But it is expanding instead. :(
JSFiddle: http://jsfiddle.net/7vfjet1g/

I think what you're looking for is an elastic text area. There are a few JavaScript libraries that provide this functionality:
https://github.com/chemerisuk/better-elastic-textarea
https://github.com/chrisgeo/elastic-textarea
http://unwrongest.com/projects/elastic/
It's not much code, but a careful combination of JavaScript and CSS. If for some reason you don't want to add another library to your project, or this doesn't fit your requirement, it may point you in the right direction. Good luck.

I tested out your existing code, and the values that scrollWidth and scrollHeight were giving you were much bigger than the size of the actual text.
One way to get the size of the actual text is to create a span with the same font styling as the text area, copy over the value of the textarea to it, then append the span to the document. You can then use getBoundingRect() to get the dimensions of the span, and thus the dimensions of the text in your textarea.
NOTE: I changed the id of your enclosing div. It had the same id as the textarea, and ids are supposed to be unique. Having two elements with the same id could cause problems with the javascript. Here's the jsfiddle: https://jsfiddle.net/yog8kvx7/7/. And here's the updated blur function:
$('.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);
});
And if you want to account for the little sizing handle, so it doesn't cover the text, you can just add an offset to the width to account for it.

Related

CSS property, height, not dynamically changing to account for text height

Here's the code on JSFiddle.
Here's the script.
function toggle(divId, tog) {
var div = document.getElementById(divId);
div.classList.toggle(tog);
}
function toggleSize(divId, tog, textId) {
var div = document.getElementById(divId);
div.classList.toggle(tog);
div.getElementsByClass(tog)[0].style.height = window.getComputedStyle(textId).getPropertyValue('height');
}
What I tried doing is get the height value of the contained text, and assign that to the outer div.
But, the height is not updating.
Another way to word it is that I want the height to adjust to the overflowed content.
Any ideas?

div box size css show the value of auto

Help is really wanted here, I have a div surrounding a textarea, the div is auto sized, height and width, and I need to know what that auto value is. tried a little javascript, please see below:
function textAreaChange() {
var textboundary = document.getElementById("textarea");
textboundary.style.height = document.getElementById("heightx").innerHTML;
textboundary.style.width = document.getElementById("widthy").innerHTML;
}
fairly new to all this javascript so please be patient?
Thanks.
If you are looking at obtaining the height and width, based on wrapping of the text area, try one of the following:
var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
clientHeight includes the height and vertical padding.
offsetHeight includes the height, vertical padding, and vertical borders.
scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
There are Widths that correspond to each Height.
You can do it like this :)
function textAreaChange() {
var textboundary = document.getElementById("textarea");
document.getElementById("heightx").innerHTML = textboundary.offsetHeight;
document.getElementById("widthy").innerHTML = textboundary.offsetWidth;
}
textAreaChange();
<textarea id="textarea" ></textarea>
<div id="heightx"></div>
<div id="widthy"></div>

How to set the font-size to 100% the size of a div?

I have a div with a static size. Sometimes longer text than the div will be placed there. Is there anyway to achieve the text fitting the div width at all times through JavaScript alone? I am aware there are jQuery fixes but need a pure JS solution in this case.
Even if you have a link to a demo/tutorial that would be helpful, thanks.
Here you go, this should do what you want: JSFiddle
Basically the key here is to check the output.scrollHeight against output.height. Consider the following setup:
HTML:
<button onclick="addText(); resizeFont()">Click Me to Add Some Text!</button>
<div id="output"></div>
CSS:
div {
width: 160px;
height: 160px;
}
This creates a square div and fills it with a randomly long string of text via the addText() method.
function addText() {
var text = "Lorem ipsum dolor amit",
len = Math.floor(Math.random() * 15),
output = document.querySelector('#output'),
str = [];
for (; --len;)
str.push(text);
output.innerHTML = str.join(', ');
}
The magic lies in the resizeFont() function. Basically what this does is, once the text has been added, it sets the fontSize of the div to be equal to its own height. This is the base case for when you have a string of 1 character (i.e. the fontSize will equal the height). As the length of your string grows, the fontSize will need to be made smaller until the scrollHeight equals the height of the div
function resizeFont() {
var output = document.querySelector('#output'),
numRE = /(\d+)px/,
height = numRE.exec(window.getComputedStyle(output).height)[1],
fontSize = height;
// allow div to be empty without entering infinite loop
if (!output.innerHTML.length) return;
// set the initial font size to the height of the div
output.style.fontSize = fontSize + 'px';
// decrease the font size until the scrollHeight == height
while (output.scrollHeight > height)
output.style.fontSize = --fontSize + 'px';
}
The nice thing about this method is that you can easily attach an event listener to the resize event of the window, making the text dynamically resize as the user changes the window size: http://jsfiddle.net/QvDy8/2/
window.onload = function() {
window.addEventListener('resize', resizeFont, false);
}

fill Content(html) in div for fix height and widhth using javascript and jquery

I am getting long text using ajax in json form I want to fill those content in the fix height div
suppose I have div height 500px and width 300px. and font size is 16px
i want any javascript recursive method that can fill data according to height and width of div and can return me remaining text.
if any one can do that then Please provide me solution.
Thanks in Advance
First of all, wrap the text inside a <span> in put it in your <div>. I'm assuming that div is your fixed size element here:
// Be careful about text nodes, or use firstElementChild instead
var span = div.firstChild, text = span.innerText, rest = "";
if (span.offsetHeight > 500) {
var totalLength = 0, markLength, i = 0,
rects = span.getClientRects();
for (; i < rects.length; i++) {
totalLength += rects[i].right - rects[i].left;
if (rects[i].bottom - rects[0].top <= 500)
markLength = totalLength;
}
var mark = Math.floor(text.length * markLength / totalLength);
span.textContent = text.substring(0, mark);
rest = text.substring(mark);
}
The variable rest contains the remaining part.
Beware that this method uses some approximations, and sometimes may not fill the container to the brim. In some unlucky cases, it may even overflow the container, so you have to run it again until you get the correct size.
Why don't just put all in the div and in the div you set
overflow="hidden"
Create a temp div, fix it width and append text until it exceed your height then stop, after that copy all content to the main div
var s = 'Your long long long long long long long long long long content';
var i = 0;
var tmpdiv = $('<div style="width:50px; height:auto; position:absolute; left:-99999px"/>').appendTo(document.body);
while (i < s.length-1 && tmpdiv.height() < 50){
tmpdiv.append(s[i]);
i++;
}
$('#fixdiv').html(tmpdiv.html());

How to find actual rendered values of elements set to 'auto' using JavaScript

Suppose I have the following html, and no CSS
<div>
here is some content in this div. it stretches it out
<br />and down too!
</div>
Now I want to get the actual pixel width and height that the browser has rendered this div as.
Can that be done with JS?
Thank you.
Try getting a reference to your div and reading the offsetWidth and offsetHeight properties:
var myDiv = document.getElementById('myDiv');
var width = myDiv.offsetWidth; // int
var height = myDiv.offsetHeight;
offsetWidth/Height cumulatively measures the element's borders, horizontal padding, vertical scrollbar (if present, if rendered) and CSS width. It's the pixel values of the entire space that the element uses in the document. I think it's what you want.
If that is not what you meant, and you'd rather only the element's width and height (i.e. excluding padding, margin, etc) try getComputedStyle:
var comStyle = window.getComputedStyle(myDiv, null);
var width = parseInt(comStyle.getPropertyValue("width"), 10);
var height = parseInt(comStyle.getPropertyValue("height"), 10);
The values above will be the final, computed pixel values for the width and height css style properties (including values set by a <style> element or an external stylesheet).
Like all helpful things, this won't work in IE.
You say you are using jQuery. Well it's trivial now, and works cross-browser:
var width = $('div').css('width');
var height = $('div').css('height');
With jQuery you don't need the first part of this answer, it's all taken care of for ya ;)
One of the benefits of using a framework, like Prototype, is that the framework authors have usually sorted out the portability issues. Even if you don't use the framework, it can still be instructive to read. In the case of Prototype, the code for reading the dimensions of an element accounts for a Safari issue and allows you to read the width of an element that is not presently dislayed.
getDimensions: function(element) {
element = $(element);
var display = $(element).getStyle('display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
For the jQuery framework, .height and .width do the job.

Categories

Resources