How to create reusable function with alternating if statements - javascript

I am creating a smooth scrolling and a bounce (at top and bottom) effect. (After a full day of trial and error,) I was able to successfully implement it. I'm now having trouble finding a method to have reusable clean code. (I think that's called an algorithm?)
The specific problem I'm having, is alternating between <= and >=. The code overall can use some clean up, which I did to the best of my ability, but I think it needs some more (let me know if it doesn't).
So in reusable function, like this:
function reusableFunction() {
...
if (num1 >= num2) // One case I have to compare like this
if (num1 <= num2) // Another case, I have to compare like this
...
}
I got stuck at line #86 in the function bounceBack. If you have a better way of making the smooth scrolling, and bouncing effect, please post as an answer. I don't want to use any librarys, or other frameworks (like JQuery).
JSFiddle
console.clear();
var innerWrapper = document.getElementById('innerWrapper');
innerWrapper.addEventListener('mousewheel', handleScroll);
innerWrapper.style.transform = 'translate3d(0px, 0px, 0px)';
var interval, // scroll is being eased
mult = 0, // how fast do we scroll
dir = 0, // 1 = scroll down, -1 = scroll up
steps = 50, // how many steps in animation
length = 30; // how long to animate
var bouncePadding = 30;
function handleScroll(e) {
e.preventDefault();
clearInterval(interval); // cancel previous animation
++mult; // we are going to scroll faster
var delta = -Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
if (dir != delta) { // scroll direction changed
mult = 1; // start slowly
dir = delta;
}
var start = parseInt(innerWrapper.style.transform.split(',')[1], 10); // Get x from translate3d
var end = start + length * mult * delta; // where to end the scroll
var change = end - start; // base change in one step
var step = 0; // current step
var scrolledToBottom = innerWrapper.scrollHeight - innerWrapper.parentElement.offsetHeight;
var tempVar;
interval = setInterval(function() {
var scrollPosition = easeOut(step++, start, -change, steps);
scrollPosition = clamp(scrollPosition, -scrolledToBottom - bouncePadding, 0 + bouncePadding);
innerWrapper.style.transform = 'translate3d(0px, ' + scrollPosition + 'px, 0px)';
if (tempVar === scrollPosition) {
step = steps;
} else {
tempVar = scrollPosition
}
if (step >= steps) { // scroll finished without speed up - stop by easing out
endScrollCallback();
if (scrollPosition > 0 && dir === -1) {
step = 0;
var myInterval = setInterval(function() {
var scrollPos = easeOut(step++, scrollPosition, -scrollPosition, 15);
innerWrapper.style.transform = 'translate3d(0px, ' + (scrollPos) + 'px, 0px)';
if (scrollPos <= 0) {
clearInterval(myInterval);
innerWrapper.style.transform = 'translate3d(0px, ' + (0) + 'px, 0px)';
}
}, 10);
} else if (scrollPosition < -scrolledToBottom && dir === 1) {
step = 0;
var myInterval = setInterval(function() {
var change = -scrolledToBottom - scrollPosition;
var scrollPos = easeOut(step++, scrollPosition, change, 15);
innerWrapper.style.transform = 'translate3d(0px, ' + (scrollPos) + 'px, 0px)';
if (scrollPos >= -scrolledToBottom) {
clearInterval(myInterval);
innerWrapper.style.transform = 'translate3d(0px, ' + (-scrolledToBottom) + 'px, 0px)';
}
}, 10);
}
}
}, 10);
}
function easeOut(t, b, c, d) {
t /= d;
return -c * t * (t - 2) + b;
}
function endScrollCallback() {
mult = 0;
clearInterval(interval);
}
function bounceBack(from, to, difference) {
var step = 0;
var interval = setInterval(function() {
var scrollPos = outQuartic(step++, from, difference, 15);
innerWrapper.style.transform = 'translate3d(0px, ' + (scrollPos) + 'px, 0px)';
if (scrollPos <= 0) { /* Got stuck here */
clearInterval(interval);
innerWrapper.style.transform = 'translate3d(0px, ' + to + 'px, 0px)';
}
}, 10);
}
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);
}
body {} #outerWrapper {
width: 500px;
height: 400px;
overflow: hidden;
background-color: black;
}
#content {
background-image: url("http://images.freeimages.com/images/premium/previews/3037/30376024-beautiful-flower-portrait.jpg");
}
<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 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
</div>
</div>
</div>

Generally, to customize a function, which is what <= is, one can use a function. If you'd like customize a statement like:
if (a <someFunction> b){
// ...
}
where someFunction in your case can be either <= or >, one way to do it could be:
function f(a,b,conditionsMet){
return conditionsMet ? a <= b : a > b;
}
and then call it:
if ( f(a,b,are conditions met?) ){
// ...
}
(Not sure if that's what you mean, feel free to comment..)

Related

How to count chars in a CSS limited div with JS

I have the following CSS:
html {
--lh: 18px;
}
.line-10 {
--max-lines: 10;
max-width: 100%;
max-height: calc(var(--lh) * var(--max-lines));
overflow: hidden;
}
and want to count chars in a div:
const div = document.createElement('div')
div.classList.add('line-10')
div.innerHTML = longHtml
const _createdHTML = div.innerHTML
const _createdTxt = _createdHTML.replace(/<[^>]*>/g, '')
console.log('_createdTxt', _createdTxt.length)
but I am getting the entire longHtml instead of limited by CSS. Any way to solve that?
Current solution for case A (1 big paragraph of text per div):
const maxLines = 10
const fullTxtLen = html.replace(/<[^>]*>/g, '').length
const fullLineLen = 150 // or whatever fits into initial div
if (fullTxtLen / fullLineLen > maxLines) {
const totalLines = fullTxtLen / fullLineLen
const reduceIn = totalLines / maxLines
const final = fixHtml(html.substring(0, parseInt(html.length / reduceIn)))
return {
html: final,
len: final.replace(/<[^>]*>/g, '').length // i.e. this is the answer on visible char count
}
}
function fixHtml (html) {
const div = document.createElement('div')
div.innerHTML = html
return (div.innerHTML)
}
Problems with this solution:
than introducing more <p> and/ or <br />, it will make it pretty unreliable due to different fullLineLen for each line that does not end that the div right border.
reduced char length is in text characters, not html characters
FAQ
how many characters you need to keep, input examples and expected outputs
It depends on the size of the div. Input examples: 1) lorem ipsum in one paragraph, 2) lorem ipsum broken into different paragraphs. Expected output - visible char count.
If we copy characters from the string gradually into a div that is offscreen with the same max-height (+1px) as div, intersectionObserver will let us know when it just enters the top of the screen. This will be when the first characters from the line after the last visible line are copied.
We have to let the system have a space in which it can tell us of such an observation so the copying has to be done in bits. This snippet copies a word at a time so on most systems it probably can count at a maximum of 60 words per second.
There are some uncertainties - what do we mean by a character being visible and what does the system mean? On a system in which there are accurately 10 lines in the visible portion and without scrolling the counting is accurate (concurs with e.g. Word or Notepad++).
On scrolling it is quite possible that just part of the characters in the top line and in the bottom line are shown (sometimes not really perceptibly), so what the system and what a human thinks is visible and should be counted may differ. It is not clear from the question what the expected result should be. This snippet does its best in the scrolled situation by counting characters that have been scrolled out at the top to adjust the overall count.
Tested on Edge/Chrome on Windows 10 and Safari on IOS 14.4. Note that on Chrome's dev tools emulators it does not work well (counts a few too many characters) as the emulation of intersectionObserver seems to be a bit laggy.
<head>
<style>
html {
--lh: 18px;
}
* {
margin: 0;
}
.line-10, .workSpaceDiv {
margin: 0 20px;
--max-lines: 10;
max-width: 100%;
max-height: calc(var(--lh) * var(--max-lines));
overflow-y: scroll;
}
.workSpaceDiv {
position: absolute;
--maxh: calc(var(--lh) * (var(--max-lines) + 1));
max-height: var(--maxh);
transform: translateY(calc(2px - var(--maxh)));
height: auto;
display: none;
}
.clickme, .info {
padding: 10px;
}
.infoblock {
padding: 20px;
}
</style>
</head>
<body>
<div class="workSpaceDiv"></div>
<div class="infoblock">
<button class="clickme" onclick="countChs(div);">Click me to count the visible characters</button>
<span class="info"> Number of visible characters: </span><span class="count"></span>
</div>
<script>
const div = document.createElement('div');
div.classList.add('line-10');
document.body.appendChild(div);
const longHtml = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mi in nulla posuere sollicitudin. Sed nisi lacus sed viverra tellus in. Sit amet consectetur adipiscing elit pellentesque habitant morbi tristique. Enim lobortis scelerisque fermentum dui faucibus. Varius duis at consectetur lorem donec massa sapien faucibus et. Libero enim sed faucibus turpis in eu mi bibendum. Eleifend donec pretium vulputate sapien nec sagittis aliquam malesuada bibendum. Nulla aliquet enim tortor at auctor. Mattis pellentesque id nibh tortor. Ullamcorper sit amet risus nullam eget felis. In ornare quam viverra orci sagittis eu. Pellentesque habitant morbi tristique senectus. Amet cursus sit amet dictum sit amet justo. Sit amet nulla facilisi morbi tempus. Dolor sit amet consectetur adipiscing elit duis tristique sollicitudin nibh. Facilisi morbi tempus iaculis urna id volutpat lacus laoreet. Mi in nulla posuere sollicitudin aliquam ultrices. Diam quis enim lobortis scelerisque fermentum dui faucibus in ornare. Sed augue lacus viverra vitae congue eu. Et malesuada fames ac turpis egestas integer eget aliquet nibh. Ipsum faucibus vitae aliquet nec ullamcorper. Felis bibendum ut tristique et egestas quis ipsum suspendisse ultrices. Ac felis donec et odio pellentesque diam volutpat commodo. Mauris a diam maecenas sed. Facilisis sed odio morbi quis commodo odio aenean sed. Lorem mollis aliquam ut porttitor leo a. Vivamus at augue eget arcu dictum varius duis. Nisi porta lorem mollis aliquam ut. Habitant morbi tristique senectus et netus et malesuada fames ac. Tempus iaculis urna id volutpat lacus laoreet non curabitur. Sed risus pretium quam vulputate dignissim suspendisse in. Malesuada fames ac turpis egestas maecenas pharetra. Malesuada fames ac turpis egestas maecenas. Urna nunc id cursus metus aliquam eleifend mi in. Convallis posuere morbi leo urna molestie at elementum. Facilisis leo vel fringilla est ullamcorper eget nulla facilisi. Nulla pharetra diam sit amet nisl suscipit. Posuere morbi leo urna molestie at. Risus pretium quam vulputate dignissim. Arcu dui vivamus arcu felis bibendum ut tristique et. Varius duis at consectetur lorem donec massa sapien faucibus et. Id eu nisl nunc mi ipsum faucibus vitae aliquet. Congue mauris rhoncus aenean vel elit scelerisque mauris. Nulla at volutpat diam ut venenatis tellus in. Tellus cras adipiscing enim eu turpis egestas pretium aenean pharetra. Leo integer malesuada nunc vel risus. Tortor at auctor urna nunc id cursus metus aliquam eleifend. Felis bibendum ut tristique et egestas quis ipsum. A condimentum vitae sapien pellentesque habitant morbi. Purus non enim praesent elementum facilisis leo vel fringilla. Sagittis purus sit amet volutpat consequat mauris nunc. Sed tempus urna et pharetra pharetra massa massa. Vitae proin sagittis nisl rhoncus mattis rhoncus. Non curabitur gravida arcu ac tortor dignissim convallis. Dolor sit amet consectetur adipiscing elit. Dignissim enim sit amet venenatis urna cursus. Neque ornare aenean euismod elementum nisi quis eleifend quam. Tortor at auctor urna nunc id cursus metus aliquam eleifend. Curabitur gravida arcu ac tortor dignissim convallis aenean. Neque viverra justo nec ultrices dui sapien eget mi.`;
const createdTxt = longHtml.replace(/<[^>]*>/g, '');
div.innerHTML = createdTxt;
const workSpaceDiv = document.querySelector('.workSpaceDiv');
const info = document.querySelector('.info');
const count = document.querySelector('.count');
let nextCh, lastWordSize, stopCount, scrolledChs, firstTime, scrolled, allChs;
function countChsIn() {
stopCount = false;
nextCh = 0;
lastWordSize = 0;
observer.observe(workSpaceDiv);
requestAnimationFrame(nextChFill);
function nextChFill() {
if (stopCount) return;
lastWordSize = 0;
let i, ch;
for (i = 0; i < 10; i++) {
ch = allChs.charAt(nextCh);
workSpaceDiv.innerHTML = workSpaceDiv.innerHTML + ch;
nextCh++;
lastWordSize++;
if ((!((/[a-zA-Z]/).test(ch))) || (nextCh >= allChs.length)) { break; }
}
if (nextCh < allChs.length) requestAnimationFrame(nextChFill);
else { finish(); }
}
}
function finish() {
observer.disconnect(workSpaceDiv);
workSpaceDiv.style.height = 'auto';
workSpaceDiv.innerHTML = '';
if (firstTime) {
firstTime = false;
stopCount = false;
scrolledChs = nextCh - lastWordSize -1;
workSpaceDiv.style.transform = 'translateY(calc(1px - (var(--maxh) + ' + scrolled + 'px' + ')))';
workSpaceDiv.style.maxHeight = 'calc(var(--maxh) + ' + scrolled + 'px' + ')';
requestAnimationFrame(countChsIn);
}
else {
workSpaceDiv.style.transform = 'translateY(calc(2px - var(--maxh)))';
workSpaceDiv.style.display = 'none';
count.innerHTML = nextCh - lastWordSize - 1 - scrolledChs;
stopCount = true;
}
}
function overlap(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
finish();
}
});
}
let observer = new IntersectionObserver(overlap);
function countChs(el) {
allChs = el.innerHTML;
scrolled = el.scrollTop;
firstTime = !(scrolled <= 0);
count.innerHTML = '...counting...';
workSpaceDiv.style.display = 'block';
workSpaceDiv.style.innerHTML = '';
workSpaceDiv.style.height = 'auto';
if (firstTime) {
workSpaceDiv.style.transform = 'translateY(calc(2px - ' + scrolled + 'px' + '))';
workSpaceDiv.style.maxHeight = scrolled + 'px';
}
else {
workSpaceDiv.style.transform = 'translateY(calc(2px - var(--maxh)))';
workSpaceDiv.style.maxHeight = 'var(--maxh)';
}
scrolledChs = 0;
requestAnimationFrame(countChsIn);
}
</script>
</body>

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/

Custom scrollbars thumb goes out of bounds

I am trying to create a thumb scroller that scrolls together with the default scroller (with animation). I wan finally able to implement it, be the only problem is, the custom scroller doesn't scroll at the exact position. If you scroll all the way down, the thumb scroller goes past its parent element.
Also, the thumb scroller is larger than the default scroller. Here's the math:
scrollBarThumb.style.height = (innerWrapper.parentElement.offsetHeight * innerWrapper.parentElement.offsetHeight / innerWrapper.scrollHeight) + 'px';
scrollBarPosition = clamp(scrollBarPosition, 0, scrolledToBottom)
scrollBarPosition = scrollBar.offsetHeight * scrollBarPosition / innerWrapper.scrollHeight;
The formulas I used are the accepted formulas for custom scrollers.
The two problems are: (they may be one issue, because I think if the height gets fixed, then the scrolling position will automatically get fixed as well.) First, the scrollers thumb is larger than the default. Second, the scrollers thumb goes past its parent when you scroll all the way down.
What am I doing wrong, and how can I fix it?
JSFiddle
console.clear();
var innerWrapper = document.getElementById('innerWrapper');
var scrollBar = document.getElementById('scrollbar');
var scrollBarThumb = scrollBar.firstElementChild
scrollBarThumb.style.height = (innerWrapper.parentElement.offsetHeight * innerWrapper.parentElement.offsetHeight / innerWrapper.scrollHeight) + 'px';
innerWrapper.addEventListener('mousewheel', handleScroll);
innerWrapper.addEventListener('DOMMouseScroll', handleScroll);
var duration = 35,
scrollSpeed = 2,
animateAmount = 30;
var scrolledToBottom = 0,
scrollDirection = 0, // 1 = scroll down, -1 = scroll up
animationID;
function handleScroll(e) {
// Cancel previous animation
cancelAnimationFrame(animationID);
// Scroll faster
scrollSpeed += 2;
// Reason for negative `-.wheelDelta` because Firefox
// return oposite value. See http://phrogz.net/js/wheeldelta.html
// Get 1 or -1
var delta = Math.max(-1, Math.min(1, (-e.wheelDelta || e.detail)));
// Check if scroll direction changed
if (scrollDirection != delta) {
scrollSpeed = 2; // Start slowly - restart speed
scrollDirection = delta;
}
var start = innerWrapper.parentElement.scrollTop,
end = start + animateAmount * scrollSpeed * delta, // Where to end the scroll
change = end - start, // base change in one scroll
step = 0, // current step in animation
tempScrollPosition; // Cannot assign any number yet (i.e. 0), because `scrollPosition` may be 0.
// Get amount of scrolled to bottom
scrolledToBottom = innerWrapper.scrollHeight - innerWrapper.parentElement.offsetHeight;
animationID = requestAnimationFrame(smoothScrollAnim); // Start animation
function smoothScrollAnim() {
animationID = requestAnimationFrame(smoothScrollAnim); // Restart animation
// Get scroll position
var scrollBarPosition = easeOut(step++, start, change, duration);
scrollBarPosition = clamp(scrollBarPosition, 0, scrolledToBottom)
scrollBarPosition = scrollBar.offsetHeight * scrollBarPosition / innerWrapper.scrollHeight;
// Apply scroll movement
scrollBarThumb.style.top = scrollBarPosition + 'px';
// Check if scroll finished (either animation finished, or bumped to top or bottom)
if (step >= duration || tempScrollPosition === scrollBarPosition) {
// Clean up
tempScrollPosition = null;
scrollSpeed = 2;
cancelAnimationFrame(animationID);
} else {
tempScrollPosition = scrollBarPosition;
}
}
}
function easeOut(time, begin, change, duration) {
time /= duration;
return -change * time * (time - 2) + begin;
}
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);
}
html {
height: 100%;
overflow-y: hidden;
}
body {
height: 100%;
overflow-y: hidden;
display: flex;
}
#outerWrapper {
height: 400px;
overflow: auto;
background-color: black;
}
#content {
background-image: url("http://images.freeimages.com/images/premium/previews/3037/30376024-beautiful-flower-portrait.jpg");
width: 400px;
}
#scrollbar {
height: 400px;
width: 50px;
background-color: orange;
border: 2px solid green;
}
#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 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
</div>
</div>
</div>
<div id="scrollbar">
<div id="scrollbar_thumb"></div>
</div>
For the scroll simply register the "scroll" event,
For the catching-delay effect use CSS3 transition
For the simple math involved see the example below:
const el = (sel, par) => (par || document).querySelector(sel);
const
elContent = el("#content"),
elHandler = el("#handler");
// FROM ELEMENT SCROLL TO HANDLER POSITION
const moveScrollbar = () => {
const
height = elContent.clientHeight,
scrollHeight = elContent.scrollHeight,
handlerHeight = height ** 2 / scrollHeight,
handlerTop = elContent.scrollTop / height * handlerHeight;
Object.assign(elHandler.style, {
height: `${handlerHeight}px`,
top: `${handlerTop}px`
});
}
moveScrollbar(); // At init
elContent.addEventListener("scroll", moveScrollbar); // and on scroll
* { margin: 0; box-sizing: border-box; }
#area {
display: flex;
}
#content {
height: 160px;
width: 300px;
font-size: 3rem;
background: #eee;
padding: 1rem;
}
#content {
overflow-y: scroll;
scrollbar-width: none;
-ms-overflow-style: none;
}
#content::-webkit-scrollbar {
width: 0;
height: 0;
}
#scrollbar {
flex: none;
position: relative;
background: #333;
width: 1rem;
}
#handler {
position: absolute;
top: 0;
background: orange;
width: 100%;
transition: 0.2s; /* smooth move */
}
<div id="area">
<div id="content">
Scroll and see the custom scrollbar move.<br>Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis.
</div>
<div id="scrollbar">
<div id="handler"></div>
</div>
</div>
Then, to make the handler draggable, here's the formula:
// FROM HANDLER POSITION TO ELEMENT SCROLL:
const
height = elContent.clientHeight,
scrollHeight = elContent.scrollHeight,
scrollPos = scrollHeight / height * elHandler.clientTop;

Fabric JS ITEXT Word wrap automatically when control border reach at the end of canvas

I'm using fabric js ITEXT to write on canvas. When i reach at the end of the canvas text crosses the canvas border which will not show to the user.
I need to wrap the text i have searched but not get any proper solution.
I'm also using fabric.Textbox in place of IText but still got same problem.
Please suggest any solution......
to get word wrapping, you have to override on textbox method.
Look this fiddle for inspiration:
fabric.Textbox.prototype._wrapLine = function(ctx, text, lineIndex) {
var lineWidth = 0,
lines = [],
line = '',
words = text.split(' '),
word = '',
letter = '',
offset = 0,
infix = ' ',
wordWidth = 0,
infixWidth = 0,
letterWidth = 0,
largestWordWidth = 0;
for (var i = 0; i < words.length; i++) {
word = words[i];
wordWidth = this._measureText(ctx, word, lineIndex, offset);
lineWidth += infixWidth;
// Break Words if wordWidth is greater than textbox width
if (this.breakWords && wordWidth > this.width) {
line += infix;
var wordLetters = word.split('');
while (wordLetters.length) {
letterWidth = this._getWidthOfChar(ctx, wordLetters[0], lineIndex, offset);
if (lineWidth + letterWidth > this.width) {
lines.push(line);
line = '';
lineWidth = 0;
}
line += wordLetters.shift();
offset++;
lineWidth += letterWidth;
}
word = '';
} else {
lineWidth += wordWidth;
}
if (lineWidth >= this.width && line !== '') {
lines.push(line);
line = '';
lineWidth = wordWidth;
}
if (line !== '' || i === 1) {
line += infix;
}
line += word;
offset += word.length;
infixWidth = this._measureText(ctx, infix, lineIndex, offset);
offset++;
// keep track of largest word
if (wordWidth > largestWordWidth && !this.breakWords) {
largestWordWidth = wordWidth;
}
}
i && lines.push(line);
if (largestWordWidth > this.dynamicMinWidth) {
this.dynamicMinWidth = largestWordWidth;
}
return lines;
}
var longText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean gravida consequat porta. Nullam euismod, justo interdum iaculis sodales, justo velit sodales lacus, ultrices eleifend metus mauris ut diam. Fusce imperdiet felis porta, viverra nisl id, rutrum ligula. Aliquam consequat, ante ac maximus fringilla, enim metus facilisis dui, nec cursus lacus augue ut risus. Suspendisse felis felis, placerat a suscipit vel, blandit sed lorem. Nullam laoreet, lorem vitae tempus vulputate, ex sapien porta mi, et dictum ante ex at ipsum. Phasellus semper volutpat felis in congue. Nunc aliquam sapien eu fringilla sodales. Quisque ut feugiat sem, sed vehicula justo. Mauris vitae suscipit nisi, sed pulvinar justo. Aenean non tempus nisi. Ut suscipit euismod faucibus. Donec venenatis, justo eget posuere fermentum, lorem nisl pharetra eros, sed convallis enim odio eget ligula. Suspendisse in semper magna. Nullam id sapien faucibus, congue odio quis, porttitor augue. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed malesuada maximus interdum. Nunc urna urna, dignissim non erat sed, maximus cursus arcu. Praesent tempor erat eu tellus bibendum malesuada. Vivamus est lacus, suscipit ultricies nisl vel, finibus porttitor elit. Nullam at elit sed massa maximus finibus. Morbi pulvinar lectus non ligula vehicula convallis. Praesent ultricies tellus congue eros lobortis, a scelerisque nisi pretium. Phasellus iaculis imperdiet ante, non malesuada metus varius et. Morbi laoreet velit ut auctor pulvinar. Curabitur dignissim elementum libero, finibus scelerisque velit tempor in. In eget consectetur nibh.';
var canvas = fabric.Canvas('c');
var breakingTextbox = new fabric.Textbox(longText, {
width: 300,
breakWords: true
});
canvas.add(breakingTextBox);
<script src="http://www.deltalink.it/andreab/fabric/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>

Categories

Resources