JavaScript - scrollHeight with rows attribute - javascript

I want to get the height of the text inside a textarea. Here is the problem: the textarea has a fixed number of rows, causing the scrollHeight property to become useless in this case. See this example:
console.log(document.querySelector('textarea').scrollHeight);
<textarea rows="10">Hello, world!</textarea>
My idea was to remove the rows attribute with JavaScript, retrieve the scrollHeight, and reapply the attribute.
However, this causes jumps on the page in Safari, so it is not a solution.
Does anyone know of a property/function that return this value? Thanks in advance!

To be "more or less" bullet proof, solution has to consider the real computed size of your text.
const scrollOrNot = (el, nbline) => {
const divTest = document.querySelector('#test');
divTest.style.fontsize = el.style.fontsize;
divTest.style.lineHeight = el.style.lineHeight;
divTest.style.width = el.getBoundingClientRect().width + 'px';
divTest.innerHTML = 'W';
const h_one_line = divTest.getBoundingClientRect().height;
divTest.innerHTML = el.value;
if (Math.floor((divTest.getBoundingClientRect().height / h_one_line)) > nbline) {
console.log((divTest.getBoundingClientRect().height / h_one_line));
el.setAttribute('rows', 10);
}
}
scrollOrNot(document.querySelector('#textarea1'),10);
scrollOrNot(document.querySelector('#textarea2'),10);
#test {
position: absolute;
top: -3000px;
height: auto;
}
<textarea id="textarea1">Hello, world!</textarea>
<textarea id="textarea2">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Turpis massa tincidunt dui ut ornare lectus. Pellentesque dignissim enim sit amet venenatis urna. In fermentum posuere urna nec tincidunt. Venenatis urna cursus eget nunc scelerisque viverra mauris in. Non quam lacus suspendisse faucibus interdum posuere lorem ipsum. Nunc id cursus metus aliquam eleifend mi in nulla. Netus et malesuada fames ac turpis egestas integer eget. Sit amet dictum sit amet justo donec enim diam. Aliquam purus sit amet luctus venenatis lectus. Ligula ullamcorper malesuada proin libero nunc. Venenatis lectus magna fringilla urna porttitor rhoncus. Faucibus interdum posuere lorem ipsum dolor. Posuere ac ut consequat semper viverra nam libero justo laoreet. Ac turpis egestas sed tempus urna et pharetra pharetra massa. Vestibulum sed arcu non odio euismod lacinia. Arcu non odio euismod lacinia at quis risus sed. Lobortis mattis aliquam faucibus purus in massa tempor nec. Enim ut sem viverra aliquet eget sit amet tellus cras.
</textarea>
<div id="test"></div>
here you have a div at -3000px, absolute.
you put same width, fontsize and line height of your textarea.
You put a 'W' in it (biggest letter for latin character)
you take it's height
you put your text in
you take the new height
if division more than requested lines...

Related

It seems <html> element is like a pseudo window element or view container element?

If any webpage has 3000px tall of content, I would have expected both
document.body.offsetHeight
document.documentElement.offsetHeight
to be both 3000px. Note that document.documentElement is exactly the same as the <html> element:
document.documentElement === document.querySelector("html") // true
However, document.documentElement.offsetHeight is not 3000px. It is merely 800px or 600px (as tested on the current StackOverflow page), and it just depends on how tall the window of the content area (or viewport) roughly is.
In fact, document.documentElement.scrollTop changes when the webpage is scrolled up. document.body.scrollTop remains 0 all the time.
This is exactly the same behavior as if there is a container div of 200px × 200px, with overflow set to auto or scroll, and then the content div inside the container div is 2000px × 2000px. In such case, the container div has a small clientHeight or offsetHeight (about 200px) and scrollTop changes when the content is scrolled up and down.
Is this how it is originally designed to be? Maybe for many years I thought <html> and <body> elements have almost the same: the content displayed to user is the same (<head> isn't displayed) and their height and width are the same and it was a misconception? It feels like the design principle is that <html> is like a view container or a pseudo window.
Even the CSS participated in this:
getComputedStyle(document.documentElement)["height"] // 600px or small number
getComputedStyle(document.body)["height"] // 3000px
But perhaps one strange behavior is, if I add a scroll event listener, I have to add it to document or window but not document.documentElement:
document.documentElement.addEventListener("scroll", ... // won't work
And it is different if it is the case for the 200px × 200px container case above. The event handler would be added to this 200px × 200px container.
Example involving document.documentElement.scrollTop and document.documentElement.scrollHeight (when everything is scrolled up, then the background becomes yellow):
document.addEventListener("scroll", ev => {
// console.log(ev);
document.body.style.background = document.documentElement.scrollTop + document.documentElement.clientHeight === document.documentElement.scrollHeight ? "yellow" : "white";
})
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Dui sapien eget mi proin sed libero enim. Vel risus commodo viverra maecenas accumsan lacus vel. Magnis dis parturient montes nascetur. Amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Nullam non nisi est sit amet facilisis magna etiam. Porttitor leo a diam sollicitudin tempor id eu. Turpis egestas sed tempus urna et pharetra pharetra massa massa. Phasellus egestas tellus rutrum tellus pellentesque. Arcu odio ut sem nulla pharetra diam. Felis imperdiet proin fermentum leo vel orci. Id donec ultrices tincidunt arcu non. Egestas pretium aenean pharetra magna ac placerat. Amet risus nullam eget felis.
Laoreet id donec ultrices tincidunt arcu non sodales neque. Dolor magna eget est lorem ipsum dolor. Interdum consectetur libero id faucibus nisl. Amet purus gravida quis blandit turpis cursus in hac habitasse. Ultrices gravida dictum fusce ut placerat. Tortor consequat id porta nibh venenatis cras sed felis. Sagittis eu volutpat odio facilisis mauris sit. Massa placerat duis ultricies lacus sed turpis tincidunt id aliquet. Vel quam elementum pulvinar etiam non quam lacus. Blandit turpis cursus in hac habitasse platea dictumst.
Amet justo donec enim diam vulputate. Cursus mattis molestie a iaculis at. Massa massa ultricies mi quis hendrerit dolor. Est ultricies integer quis auctor elit. Id venenatis a condimentum vitae. Amet mauris commodo quis imperdiet. Pretium viverra suspendisse potenti nullam ac. Ultrices dui sapien eget mi. Mattis molestie a iaculis at erat pellentesque adipiscing. Commodo quis imperdiet massa tincidunt. Arcu non sodales neque sodales. Nibh tortor id aliquet lectus proin. Nam at lectus urna duis convallis convallis. Faucibus nisl tincidunt eget nullam non nisi.
</div>
I got very different results for the following
console.log(document.body.offsetHeight);
console.log(document.documentElement.offsetHeight);
inside the current StackOverflow webpage (using Google Chrome's developer console). But if I create a very long plain HTML file, and do the above two lines in its <script> or in developer's console, I got similar numbers for <body> and <html>. So I am confused why a plain page and StackOverflow behave differently. It seems <html> can be used as a pseudo window or not as one.
But inside the long plain HTML page, if I do:
console.log(document.body.clientHeight);
console.log(document.documentElement.clientHeight);
I was able to get 2400px for the and 680px for <html>. So it looks like it is still using <html> as a pseudo window or view container. But I thought clientHeight and offsetHeight are very close but just the scrollbar size is included in offsetHeight. I wonder why they are so different in this case.
Example:
console.log(document.body.clientHeight);
console.log(document.documentElement.clientHeight);
body { font-size: 36px; }
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. At quis risus sed vulputate odio ut enim blandit. Dolor sed viverra ipsum nunc aliquet bibendum enim facilisis gravida. Sit amet purus gravida quis blandit. Et ultrices neque ornare aenean euismod elementum. Varius duis at consectetur lorem donec massa sapien faucibus et. In iaculis nunc sed augue. Platea dictumst quisque sagittis purus sit amet. Tortor at risus viverra adipiscing at in tellus. Mauris commodo quis imperdiet massa tincidunt nunc pulvinar sapien. Rhoncus est pellentesque elit ullamcorper dignissim cras. Porttitor lacus luctus accumsan tortor posuere. Velit sed ullamcorper morbi tincidunt ornare massa eget egestas. Sed nisi lacus sed viverra tellus. Et ligula ullamcorper malesuada proin libero. Velit scelerisque in dictum non consectetur a erat nam. Non tellus orci ac auctor augue mauris augue neque gravida. Proin libero nunc consequat interdum varius sit. Hac habitasse platea dictumst quisque sagittis purus sit amet.
Dolor morbi non arcu risus. Elit duis tristique sollicitudin nibh sit amet commodo nulla. Tincidunt praesent semper feugiat nibh sed pulvinar. Amet consectetur adipiscing elit pellentesque habitant morbi tristique. Feugiat scelerisque varius morbi enim nunc faucibus a pellentesque sit. Lectus mauris ultrices eros in cursus turpis massa tincidunt dui. Sit amet nisl suscipit adipiscing. Amet nulla facilisi morbi tempus iaculis. Suspendisse sed nisi lacus sed viverra. Nullam ac tortor vitae purus. Risus quis varius quam quisque id diam vel quam. Enim ut sem viverra aliquet eget. Ridiculus mus mauris vitae ultricies leo integer malesuada nunc vel. Dictum varius duis at consectetur lorem donec massa. Eu feugiat pretium nibh ipsum consequat nisl vel. Amet risus nullam eget felis eget nunc lobortis. Egestas purus viverra accumsan in nisl.
Dignissim diam quis enim lobortis. Eget duis at tellus at urna condimentum mattis pellentesque. Eu nisl nunc mi ipsum faucibus vitae aliquet nec. Lectus urna duis convallis convallis tellus id interdum velit laoreet. Velit ut tortor pretium viverra suspendisse. Euismod in pellentesque massa placerat duis ultricies lacus sed turpis. Et sollicitudin ac orci phasellus egestas tellus rutrum tellus pellentesque. Id faucibus nisl tincidunt eget nullam non nisi est. Ut venenatis tellus in metus vulputate. Lectus proin nibh nisl condimentum. Bibendum at varius vel pharetra vel. Quam vulputate dignissim suspendisse in. Ut etiam sit amet nisl purus in mollis nunc. Blandit volutpat maecenas volutpat blandit aliquam etiam erat velit scelerisque.
Ac ut consequat semper viverra nam libero justo. Lacus vel facilisis volutpat est velit egestas. Amet aliquam id diam maecenas ultricies. Enim tortor at auctor urna. Magna etiam tempor orci eu. Sollicitudin tempor id eu nisl nunc mi ipsum. Etiam tempor orci eu lobortis elementum nibh tellus. Velit ut tortor pretium viverra suspendisse potenti nullam ac tortor. Nulla facilisi cras fermentum odio eu feugiat pretium nibh. Eu tincidunt tortor aliquam nulla facilisi cras fermentum. Proin libero nunc consequat interdum varius sit amet mattis. Semper risus in hendrerit gravida rutrum quisque non tellus orci. Risus nullam eget felis eget nunc lobortis.
Risus sed vulputate odio ut enim blandit volutpat maecenas volutpat. In nulla posuere sollicitudin aliquam. Sagittis nisl rhoncus mattis rhoncus urna neque viverra. Sit amet justo donec enim diam vulputate. Ut faucibus pulvinar elementum integer. Interdum posuere lorem ipsum dolor sit amet consectetur adipiscing elit. A condimentum vitae sapien pellentesque habitant morbi tristique. Vel fringilla est ullamcorper eget nulla facilisi. Vitae purus faucibus ornare suspendisse sed nisi lacus sed viverra. Aenean vel elit scelerisque mauris pellentesque pulvinar pellentesque. Ultricies integer quis auctor elit sed vulputate mi. Euismod quis viverra nibh cras pulvinar mattis. Sapien pellentesque habitant morbi tristique senectus et netus et malesuada. Mi tempus imperdiet nulla malesuada pellentesque elit eget.
Tincidunt augue interdum velit euismod in pellentesque massa placerat duis. Nam libero justo laoreet sit amet. Feugiat pretium nibh ipsum consequat nisl vel pretium lectus. Facilisi etiam dignissim diam quis enim. Augue lacus viverra vitae congue eu. Velit scelerisque in dictum non consectetur a erat nam. Amet purus gravida quis blandit turpis cursus in. Tortor pretium viverra suspendisse potenti nullam ac. Dolor sit amet consectetur adipiscing elit ut. Proin sed libero enim sed faucibus turpis in eu. Amet nulla facilisi morbi tempus iaculis urna id volutpat. Ut pharetra sit amet aliquam id diam maecenas ultricies mi. At in tellus integer feugiat. Vestibulum lectus mauris ultrices eros in cursus turpis massa. Dui nunc mattis enim ut tellus. Elit duis tristique sollicitudin nibh. Ac odio tempor orci dapibus ultrices in. Netus et malesuada fames ac turpis egestas sed. Quam lacus suspendisse faucibus interdum posuere lorem ipsum. A lacus vestibulum sed arcu non odio euismod lacinia.
</div>
One thing we also need to be careful about, is as stated in JavaScript Definitive Guide 6th Ed p.395 and p.903 and on the specs, clientWidth and clientHeight behaves differently if it is on the <html> element, which is to give the viewport's width and height excluding any scrollbar. So when the page is studied, this needs to be kept in mind.
Likewise, there is even such an exception on scrollTop on <html>. It is the scrollY of window in such a case..
I think one conclusion so far is, it seems <html> is somehow treated as a pseudo window or viewing area programmatically, as how its properties are specified in the specs.
First, if here in Stack Overflow's page you get the .offsetHeight and getComputedStyle()['height'] to be the size of the viewport, it is because there is a rule stating html { height: 100%; }.
Without this rule, you'd have it the same size as the body:
console.log( "height:auto" );
console.log( "offsetHeight", document.documentElement.offsetHeight );
document.documentElement.classList.add( "SO" );
console.log( "height:100%" );
console.log( "offsetHeight", document.documentElement.offsetHeight );
body {
height: 1000vh;
}
html.SO {
height: 100%;
}
Now for the scroll related values, the document.documentElement element is the de-facto document.scrollingElement in a normal web-page:
console.log( document.scrollingElement === document.documentElement );
and it is the document.body in quirks mode.
Given this special status, the scroll related values of the scrollingElement actually return the root node's ones, which has its containing block's dimensions set to the viewport's dimensions in normal web pages.

JS detect when an html element wraps down

I would like to scroll down to an element when it is created in a div, or when the element wraps down so you can always see the entire text since the text is added slowly to the element.
I have already got a way to auto-scroll to elements when they are created using element.scrollIntoView().
this.setText = function (text) {
this.text = text
this.progress = move
this.element.innerHTML = '[Player]>'
this.element.scrollIntoView({behavior: "smooth"})
}
this.run = function () {
if (this.progress < this.text.length) {
// Add animation for different speeds of typing keys
this.progress += 0.8 * Math.random()
} else {
this.progress = this.text.length
}
// Draw the text at the current line number
const currLine = Math.floor(clamp(this.progress, 0, this.text.length))
this.element.innerHTML = '[Player]>' + this.text.slice(0, currLine)
}
That is the way I add text to the element slowly. I would like to detect the wrap instead of repeatedly scrolling into view the element
Edit: I would have liked to detect when the element wraps not see if it has wrapped i.e. something like window.onElementWrap() but I can work with what you have given me.
The way I can solve my issue is each loop checking if the height is different from the stored height, and if it is, scrolling it into view as well as setting the stored height to the current height.
You can check the element's offsetHeight (eg: this.element.offsetHeight), it will change when the text wraps to a new line.
Here is an example:
const text = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Interdum varius sit amet mattis vulputate enim nulla. Est ullamcorper eget nulla facilisi etiam dignissim diam quis enim. Pharetra pharetra massa massa ultricies mi. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Nunc mi ipsum faucibus vitae aliquet nec ullamcorper. Aliquam sem et tortor consequat id porta nibh venenatis cras. Aliquam sem et tortor consequat id porta nibh venenatis. Lectus quam id leo in. Pharetra vel turpis nunc eget lorem dolor. Euismod lacinia at quis risus sed vulputate odio. Tempus iaculis urna id volutpat lacus laoreet non. Mattis rhoncus urna neque viverra justo. Massa eget egestas purus viverra. Gravida dictum fusce ut placerat orci. In massa tempor nec feugiat. Mauris cursus mattis molestie a. Ultrices in iaculis nunc sed augue lacus viverra. Vel risus commodo viverra maecenas accumsan. Lectus nulla at volutpat diam ut venenatis tellus. Vestibulum mattis ullamcorper velit sed ullamcorper. Fermentum et sollicitudin ac orci phasellus. Justo laoreet sit amet cursus sit amet dictum. Ipsum consequat nisl vel pretium lectus quam id. Et ligula ullamcorper malesuada proin libero nunc consequat interdum. Pulvinar proin gravida hendrerit lectus. Aliquet nibh praesent tristique magna sit.`
let lines = text.match(/.{150}/g);
lines = [...lines, ...lines];
lines = [...lines, ...lines];
let index = 0;
let prevHeight = testElement.offsetHeight;
const interval = setInterval(() => {
testElement.textContent += lines[index];
const currentHeight = testElement.offsetHeight;
if (currentHeight > prevHeight) {
window.scroll(window.scrollX, window.scrollY + (currentHeight - prevHeight));
}
prevHeight = currentHeight;
index++;
if (index >= lines.length) {
clearInterval(interval);
}
}, 100);
<div id="testElement"></div>

Div goes past its parent element [duplicate]

This question already has an answer here:
Why do child divs extend beyond their parent div?
(1 answer)
Closed 6 years ago.
I'm trying to create a custom scroller, and I'm using translate3d to scroll. The only problem is, when you scroll all the way to the bottom, the thumb (scroller) goes too far down. I'm using the accepted formula, but for some reason, it goes past its parent wrapper. Here's the formula:
scrollPosition * scrollBarThumb_height / content_height
What am I doing wrong, and how can I get the thumb to fully stay in its parents view?
JSFiddle
console.clear();
var innerWrapper = document.getElementById('innerWrapper');
var scrollBar = document.getElementById('scrollbar');
var scrollBarThumb = scrollBar.firstElementChild
scrollBarThumb.style.height = (innerWrapper.offsetHeight * innerWrapper.offsetHeight / innerWrapper.scrollHeight) + 'px';
innerWrapper.addEventListener('mousewheel', handleScroll);
innerWrapper.addEventListener('DOMMouseScroll', handleScroll);
innerWrapper.style.transform = 'translate3d(0px, 0px, 0px)';
function handleScroll(e) {
// Prevent parents from scrolling
e.preventDefault();
var direction = (e.detail < 0 || e.wheelDelta > 0) ? 1 : -1; // 1 = scroll down, -1 = scroll
var start = parseInt(innerWrapper.style.transform.split(',')[1], 10);
var scrollPosition = start + direction * 100; // Cannot use `deltaY`, because not all browsers support it.
var scrolledToBottom = innerWrapper.scrollHeight - innerWrapper.parentElement.offsetHeight;
scrollPosition = clamp(scrollPosition, -scrolledToBottom, 0);
innerWrapper.style.transform = 'translate3d(0px, ' + scrollPosition + 'px, 0px)';
scrollBarThumb.style.top = -(scrollPosition * scrollBarThumb.offsetHeight / innerWrapper.parentElement.offsetHeight) + 'px'
}
function clamp(val, min, max) {
if (typeof min !== 'number') min = 0;
if (typeof max !== 'number') max = 1;
return Math.min(Math.max(val, min), max);
}
#outerWrapper {
height: 400px;
overflow: hidden;
display: flex;
}
#content {
background-image: url("http://images.freeimages.com/images/premium/previews/3037/30376024-beautiful-flower-portrait.jpg");
width: 400px;
}
#scrollbar {
height: 100%;
width: 50px;
background-color: orange;
}
#scrollbar_thumb {
background-color: yellow;
border: 2px solid blue;
position: relative;
}
<div id="outerWrapper">
<div id="innerWrapper">
<div id="content">
Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero
sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus
Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus
enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar
justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames
ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque
Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem
lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie
vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum
vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque
Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci
Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla.
Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet
consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum
vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque
Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor
</div>
</div>
<div id="scrollbar">
<div id="scrollbar_thumb"></div>
</div>
</div>
The borders were not calculated properly into the total element's height, thus creating the problem.
Simply add box-sizing: border-box; to solve the issue:
#scrollbar_thumb {
...
box-sizing: border-box;
}
working JSFiddle fork: https://jsfiddle.net/azizn/9nfns6kk/

link for max characters in javascript not working

Ive got a js that runs to see if a maximum amount of characters is reached. Its got text along with href, but when the max amount of characters is reached, the link doesnt work and converts it to just text. When the limit of less then 580 characters, link works. When it does reach the limit, the read more link does work. Any advice or help please and thanks
$(document).ready(function () {
var stylistText = $('#stylistText');
var stylistText2 = document.getElementById("stylistText").innerHTML;
var countActualText = stylistText2.valueOf().length;
var maxLength = 580;
var aElement = document.createElement('a');
var linkText = document.createTextNode(" ...Read more");
aElement.appendChild(linkText);
aElement.href = "#";
if (countActualText > maxLength) {
stylistText.text(stylistText.text().substring(0, 580));
stylistText.append(aElement);
}
});
here is the html
<div class="stylistInfo">
<img id="stylistPhoto" src="images/Test.jpg" alt="peekaboo beans stylist" />
<p id="stylistText">
This is supposed to be a link Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.
</p>
</div>
Change stylistText.text(stylistText.text().substring(0, 580));
to stylistText.html(stylistText.html().substring(0, 580));
However, truncating a block of text that contains HTML may cause other problems, especially if the truncation occurs in the middle of an element. I would recommend rethinking your whole strategy on this.

resize textbox automatically according to the content

http://jsfiddle.net/h2vMN/1/
I have a text box text inside it already, in the actual application this will be filled dynamically, but for the sake of this question it has been pre filled.
<textarea id="textarea">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed tempor commodo ornare. Donec lobortis dui sed lectus egestas tristique. Vivamus vel metus turpis, faucibus varius risus. Aenean ante mauris, ultrices id facilisis vitae, dignissim eget sem. Quisque sed justo lectus, eget aliquet leo. Curabitur in mauris et diam fermentum venenatis. Proin ullamcorper, neque a vehicula euismod, odio enim aliquam ipsum, eu tristique urna sapien nec erat.
Aliquam erat volutpat. In in lacus cursus dolor pellentesque posuere. Cras eu metus urna, a rhoncus ligula. Ut hendrerit orci in arcu dignissim id fermentum orci vulputate. Sed ante ligula, volutpat eu convallis vel, auctor in metus. Mauris euismod, metus eget venenatis sodales, risus tellus volutpat elit, et aliquet massa tellus ut sapien. Mauris tempor posuere massa et consectetur. Duis dignissim enim a nulla ultricies vitae vulputate felis commodo. Phasellus mollis est eget odio porttitor consequat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus ut nibh auctor libero sagittis semper vitae quis erat.
</textarea>​
When I run the above code, it shows a tiny text area with scroll bars all over it. In other words, completely useless in terms of being user friendly. How do I automatically resize the text box according to the amount of content their is and it has a set width of 600px.
#textarea{width:600px;}​
I would like a javascript/jquery solution.
I have tried the .autoresize solution unsuccessfully, which can be found here:
http://james.padolsey.com/demos/plugins/jQuery/autoresize.jquery.js/view
Note, the height should be resized automatically
Thy this:
$(document).ready(function(){
tx = $('#textarea')
tx.height(tx.prop('scrollHeight'));
})
DEMO
$(document).ready(function(){
var heightFudgeFactor = 10;
var id = 'tempid' + Date.now();
$('#textarea').after( $('<div>').css('font-family','monospace').css('white-space','pre-wrap').css('word-wrap','break-word').attr('id',id).css('width',$('#textarea').width()).text( $('#textarea').text() ) );
$('#textarea').css('height',$('#'+id).outerHeight() + heightFudgeFactor).next().remove();
});​
Here's one way of doing it, I'm creating a secondary div that's the height of the textarea, based on content, but you'll need to play with it a little more to get it to your actual liking
I once used this plugin: http://www.jacklmoore.com/autosize
It worked fine.

Categories

Resources