resize textbox automatically according to the content - javascript

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.

Related

How can I (re)calculate Range object's for pre-added annotation-elements in a given text

Context:
I'm currently working on a editor that also needs to be able to show 'dynamically' added annotations into it. These are not saved as part of this text/body but as seperate entities. These annotations (when rendered are basic mark-elements) are saved into a database from another page where this editable text is shown as rendered text to another group of end-users.
To be able to add annotations (from that other page) into the given text I check for the user's Range object (using window.getSelection().getRangeAt(0)) and serialize this Range-object to be able to save it (ex. 2/0:448,2/0:632). When page is being loaded I deserialize/reapply this range to the document.
(using Rangy: https://github.com/timdown/rangy)
Example of a text
<article>
<p>
Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nun<mark class="annotation" data-thread-id="47" data-encoded-range="0/0:497,0/0:519">c, quis gravida magna </mark>mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem n<mark class="annotation" data-thread-id="44" data-encoded-range="0/0:955,0/0:968">eque sed ipsu</mark>m. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum<mark class="annotation" data-thread-id="45" data-encoded-range="2/0:448,2/0:632"> purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci</mark> luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer
<mark class="annotation" data-encoded-range="6/0:74,0/2:7" data-thread-id="50">lacinia.</mark>
</p>
<h2><mark class="annotation" data-thread-id="50" data-encoded-range="6/0:74,0/2:7">Test</mark></h2>
<p>
<mark class="annotation" data-thread-id="50" data-encoded-range="6/0:74,0/2:7"> libero</mark>. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus<mark class="annotation" data-thread-id="48" data-encoded-range="0/2:231,0/2:253"> orci luctus et ultric</mark>es posuere cubilia Curae; In ac dui quis mi consectetuer lacinia.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus. Nullam accumsan lorem in dui. Cras ultricies mi eu turpis hendrerit fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia.
</p>
</article>
The problem:
Whenever any change is happening to the (editable) text an, any or all annotations become invalid (depends on where the edit is happening) because all Ranges (offsets and possibly it's start/end nodes) are different now.
The Question:
How can I 'recalculate' these serialized Range's so the offsets will stay correct with any change to the text?
What I have attempted / thought of:
simply add/decrease the offsets of 'following annotations' by 1 naively and directly in the serialized strings.
Sadly this is very error-prone and won't support many edgecases (like pasting in formatted text, deleting ranges of text, ...)
try to loop through all annotation-elements in text and try recreating Range object's
either by focussing innerText of element re-do getSelection().getRangeAt() but this gives wrong range (of inside the mark-element)
or trying to recalculating offsets and use Rangy's serializePosition(). This does not seem to give me the expected results (different nodeIndexes and incorrect offsets?)
(to illustrate attempt #2.2 a bit:
const parent = annotationElement.parentNode as Node
const subject:string = parent?.innerHTML ?? ""
const tag = annotationElement.innerHTML
? annotationElement.outerHTML.slice(0,annotationElement.outerHTML.indexOf(annotationElement.innerHTML))
: annotationElement.outerHTML
// With possible HTML tags
const newStartRaw = subject.indexOf(tag)
const newStartClean = subject.substring(0, newStartRaw).replace(/<\/?[^>]+(>|$)/g, "").length
const newEnd = newStartClean + annotationElement.innerHTML.length
// this serialized string is wrong
const serialized = rangy?.serializePosition(parent, newStartClean, referenceNode) + "," + rangy?.serializePosition(parent, newEnd, referenceNode)
)
I would really appreciate the help!
If I need to clarify more or can add anything, please do tell

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.

scrollIntoView() using smooth function on multiple elements in Chrome

element.scrollIntoView with behavior set to smooth is not working as I expect in Chrome. When it is used only on one element in a callstack, it works fine. But if it is used on multiple elements, only the last element will actually scroll.
This works fine in Firefox. Is there a workaround for this in Chrome?
const $ = (s) => document.querySelector(s)
const $$ = (s) => document.querySelectorAll(s)
const container = $(".container")
for (let i = 0; i < 2; i++) {
document.body.appendChild(container.cloneNode(true))
}
function scrollIntoView(behavior) {
for (const element of $$(".reveal")) {
element.scrollIntoView({
behavior,
block: "end"
})
}
}
$(".instant").addEventListener("click", () => scrollIntoView("instant"))
$(".smooth").addEventListener("click", () => scrollIntoView("smooth"))
$(".reset").addEventListener("click", () => {
for (const element of $$(".container")) {
element.scrollTo(0, 0)
}
})
.container {
max-height: calc(33vh - 12px);
overflow-y: auto;
}
.reveal {
color: red;
}
<button class="instant">
Instant
</button>
<button class="smooth">
Smooth
</button>
<button class="reset">
Reset
</button>
<div class="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed rhoncus elementum quam. Donec quis est volutpat, dapibus nisl at, consequat turpis. Quisque convallis nunc faucibus eros egestas, in faucibus neque fringilla. Duis aliquam, metus tempor dignissim
vestibulum, nulla elit lacinia lacus, vitae pulvinar augue diam et turpis. Aenean a velit sed elit dictum fringilla ut eu augue. Vestibulum hendrerit dolor mauris. Proin quis lacus a turpis posuere maximus. Sed lacus mauris, feugiat a iaculis porta,
lacinia vel eros. Integer tempor id tortor vitae fermentum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam lobortis efficitur massa, eu elementum nulla eleifend ut. Quisque non erat iaculis, ornare erat non, interdum sapien. Suspendisse
sit amet interdum nisl, eu maximus libero. Fusce nisi nulla, iaculis eu est a, mattis tincidunt sem. Pellentesque non orci dapibus, dignissim ipsum a, finibus metus. Quisque placerat porta neque, eget finibus lectus tempus sed. Cras non gravida urna.
Morbi pretium mauris nec erat consectetur, vitae convallis lacus consectetur. Nam venenatis diam magna, sed venenatis nisl placerat viverra. Integer et mi pellentesque risus consectetur ultrices. Phasellus iaculis risus elementum, vulputate est sed,
consectetur diam. Phasellus lobortis felis purus, sit amet mattis elit pharetra ac. Nulla at viverra leo. Maecenas a condimentum magna. Maecenas porta tellus sit amet elit fermentum tincidunt. Donec ultricies blandit enim id mollis. Sed rutrum risus
sit amet posuere varius. Suspendisse suscipit maximus ligula eget egestas. Nullam lorem neque, viverra in sollicitudin ac, cursus nec purus. Aliquam placerat, arcu sit amet tincidunt consequat, ex est lacinia tellus, ac mattis nisl sapien at enim. Cras
lacinia libero eu eleifend sodales. Praesent a erat convallis, venenatis dui ut, semper sem. Vivamus tincidunt tempor neque, at congue lacus tincidunt et. Praesent consectetur, massa tristique laoreet sollicitudin, erat diam mattis nibh, nec consequat
mauris odio ut est. Integer pharetra arcu at finibus congue. Proin pellentesque fringilla blandit. Suspendisse egestas interdum nisl. Nulla facilisi. Quisque dapibus odio risus. Donec non orci dapibus risus pellentesque cursus vestibulum vel arcu. Proin
volutpat tellus sed elit auctor, sit amet tincidunt ante cursus. Donec faucibus sit amet libero sit amet lobortis. Pellentesque posuere nisl vitae pharetra vestibulum. Mauris et lobortis libero, vel facilisis metus. Duis eu venenatis dui. Fusce gravida
nibh odio, quis ullamcorper nibh rutrum sed. In dapibus, nulla non auctor egestas, nisi augue venenatis quam, et finibus lorem dui non turpis. Nullam arcu diam, mattis at erat ac, viverra lobortis felis. In in nisi magna. Ut ut ultrices velit, quis
vehicula libero. Proin dictum metus vel ante lobortis, in placerat magna ornare. Etiam vulputate metus felis, sed fringilla magna convallis vitae. Curabitur non pulvinar ante, eget molestie nibh. Quisque facilisis, diam sed dapibus blandit, ex urna
vulputate est, non auctor risus dui nec augue. Donec pretium laoreet est, tempor faucibus tortor laoreet ac.
<span class="reveal">Revealed!</span>
</div>
As per this draft at drafts.csswg.org, it is not possible to use the smooth function for scrolling multiple elements simultaneously;
When a user agent is to perform a scroll of a scrolling box box, to a given position position, an associated element element and optionally a scroll behavior behavior (which is "auto" if omitted), the following steps must be run:
Abort any ongoing smooth scroll for box.
If the user agent honors the scroll-behavior property and one of the following are true:
behavior is "auto" and element is not null and its computed value of the scroll-behavior property is smooth
behavior is smooth
...then perform a smooth scroll of box to position. Otherwise, perform an instant scroll of box to position.
Your options are:
Scroll the elements one by one using the native smooth function.
Use different API or library to animate the elements.
Functionally design the thing differently, so they don't need to scroll simultaneously.

How to create a ‘search function’ for a web page?

I’m new to jQuery/JavaScript but I have a solid idea of what I want, I’m just struggling to get it working.
I have a web page made up of different ‘div’s’ which have different ‘id’s’. I wrapped these divs in a pageContainer div. I want to be able to type a word in my ‘search bar’ and the word be looked for in the web page. It would signify a matching word by a collapsable div that would appear under the search bar which would have links to the different div id’s for where that word is. When clicked that word would be highlighted.
It’s simple but I figure it’s a good exercise to do.
Right now I know that I’m searching for the word in my pageContainer. As my understanding goes, I must search instead in each div, instead of the whole page. How can I do this?
Also as a side note, why is it that for every character I type, the search starts. Shouldn’t it only start on 3+ characters? I thought that’s what keyup does.
As of now, when I type in a word and search it, nothing happens on the web page.
/*Need to get the below search code working...*/
var thePage = $(".pageContainer");
// var content = $.makeArray(thePage.map(function(k, v){
// return $(v).text().toLowerCase();
// }));
$("#search").keyup(function(){
var input = $(this).val();
console.log(input);
//if match found, make corresponding div link appear in open collapsible div,
// else say nothing found in open collapsible div
// console.log(
thePage.filter.(function(index, value){
var foundText = $(this).val().toLowerCase();
// console.log(foundText, " BAAAAA");
console.log(index, value, " Second Here");//find 'user' input in value
// console.log(foundText.indexOf(input) >= 0);
console.log($(value).find(foundText.indexOf(input) >= 0));
// $(value).filter(foundText.indexOf(input) >= 0);
$(value).find(foundText.indexOf(input) >= 0);
var highlight = '<span class="word">' + value + '</span>';
});
// );
});
Interesting task, to sum it up the requirements are:
A web page made up of different ‘div’s’ which have different ‘id’s’.
These divs wrapped in a pageContainer div.
Type a word in my ‘search bar’ and the word be looked for in the web
page.
Signify a matching word by a collapsable div that would appear
under the search bar which would have links to the different div id’s
for where that word is.
When clicked that word would be highlighted.
Search should start on 3+ characters
I took all the above into consideration and created this codepen demo
(search for 'elementum' for example).
P.S. The highlight function is quite basic, it would be much better and safier to rely on a plugin like these.
var thePage = $(".pageContainer");
$('#results').hide(); //Hide the results div at first
$("#search").keyup(function() {
//Empty and hide the results div everytime the user types something
$('#results').empty();
$('#results').hide();
//Get the typed value
var input = $(this).val();
//Do nothing if it's smaller than three characters
if (input.length < 3) return;
//iterate through the results
var results = $(".pageContainer>div:contains('" + input + "')");
var counter = 0;
results.each(function(index, value) {
counter++;
//Get the current div that contains the given text
currentId = $(this).attr('id');
console.log('div' + index + ':' + currentId);
//Create a new element in the search div below the search input
var newP = $('<p/>', {
text: currentId
}).click(function() {
//Highlight when click
highliter(input, $(this).text());
});
$('#results').append(newP);
});
//Collapse if no results found
if (counter) $('#results').show();
else $('#results').hide();
});
function highliter(word, id) {
//Remove whatever was already highlighted
$('*').removeClass('highlight');
//Create a regular expression for the given word
var rgxp = new RegExp(word, 'g');
//Replace the plain text with a highlighted one
var repl = '<span class="highlight">' + word + '</span>';
var element = document.getElementById(id);
element.innerHTML = element.innerHTML.replace(rgxp, repl);
//Scroll to the position of the results
$('html, body').scrollTop($(".highlight").offset().top);
}
body{
background-color:grey;
}
#search{
width:200px;
}
#results{
width:200px;
border:2px solid black;
border-bottom-left-radius: 1em;
border-bottom-right-radius: 1em;
}
#results p{
background-color:#AAA;
margin: 8px;
cursor:pointer;
}
.highlight{
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="search" type="text" />
<div id="results"></div>
<hr/>
<div class="pageContainer" id="main">
SECTION_1 (first div)
<div id="section1">
<p>Mauris eget risus ipsum. Ut dignissim justo id orci efficitur, ac ultricies sem ultricies. Nullam id velit vestibulum arcu eleifend tempor non nec purus. Sed mollis metus non aliquam accumsan. Fusce venenatis urna vel elit aliquet accumsan sit amet
et velit. Cras et molestie sem, et dignissim lorem. Etiam laoreet, dui eget cursus blandit, erat nisi pulvinar erat, sed volutpat turpis ante et massa. Nunc ornare orci ut purus maximus fermentum. Fusce nisl quam, maximus nec tortor quis, sagittis
maximus velit. Morbi in enim ac augue pharetra ultricies. Ut aliquet magna tellus, non volutpat ex vulputate ac. Curabitur in enim maximus, volutpat nibh ac, auctor urna.</p>
<p>Vivamus ac lacus rutrum, suscipit mauris et, rhoncus magna. Phasellus a ante a mi fringilla interdum sed feugiat massa. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec bibendum, tellus sed lobortis ullamcorper, nibh ex maximus
lacus, egestas scelerisque diam turpis a elit. Suspendisse iaculis, massa in ultricies sollicitudin, est dui bibendum augue, non dignissim nulla nibh ut dolor. Maecenas et mollis est. Donec condimentum laoreet erat, id maximus ante imperdiet in.
Proin id purus nulla. Vivamus tincidunt facilisis nisl, eget placerat elit mattis at. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
</div>
SECTION_2(second div)
<div id="section2">
<p>Fusce sit amet sem eget elit volutpat consequat. Nulla hendrerit sem dictum volutpat convallis. Sed interdum, arcu non facilisis condimentum, ipsum purus bibendum ex, a tincidunt leo leo vel sem. Maecenas porttitor quam non tortor accumsan interdum.
In id ultrices enim. Maecenas risus arcu, egestas nec ante et, vehicula bibendum dui. Quisque nec hendrerit ante. Integer in faucibus augue. Integer imperdiet felis id tempor facilisis. Nam lobortis sem non purus luctus varius. Quisque sit amet
justo ac dui convallis efficitur eget ut mi. Sed in efficitur nisi, ac rutrum mi. In pulvinar egestas turpis, non tincidunt orci finibus nec. Sed euismod augue eu tortor pharetra maximus eget at urna. Nulla efficitur elit lacus, sit amet faucibus
justo tristique eget.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pellentesque augue non aliquam scelerisque. In tincidunt vel nisi id porttitor. Integer vulputate cursus augue. Sed luctus accumsan dui elementum eleifend. Proin convallis, sem non
accumsan pulvinar, justo lorem mattis enim, nec lobortis libero nibh nec nisi. Nulla faucibus tellus in magna rutrum, sed porttitor orci pharetra. Mauris sit amet quam enim. Sed laoreet, neque in pretium congue, neque sem tincidunt massa, sed sollicitudin
orci ex eget nisl. Donec ultrices ligula eget augue convallis, vitae sagittis mauris vulputate. Nulla non bibendum odio, a tincidunt massa. Mauris ultricies augue sit amet venenatis ornare. In pellentesque quam vitae orci pretium rutrum. Vivamus
non orci congue orci pellentesque euismod ac id dolor. Nam accumsan scelerisque sodales.</p>
</div>
SECTION_3 (third div)
<div id="section3">
<p>Ut vel eros sit amet eros accumsan imperdiet. Donec placerat urna sit amet tellus eleifend rhoncus. Pellentesque finibus dolor tortor, et dignissim tellus iaculis eu. Etiam sollicitudin mattis fermentum. Etiam porta est turpis, ut consectetur lorem
sodales eu. Aenean rutrum volutpat efficitur. Morbi a elementum lectus, id ornare orci. Fusce bibendum dignissim lacinia. Aliquam venenatis urna et leo pretium tempus. Proin ligula felis, posuere nec vestibulum quis, pellentesque ut quam. Vestibulum
sed elementum lectus. Quisque at ipsum id lacus efficitur lacinia non in lorem. Donec tristique lectus eu ex laoreet, non tristique libero blandit. Curabitur massa quam, fermentum sit amet dui non, bibendum convallis orci. Sed vulputate turpis nec
erat commodo, rhoncus cursus quam ornare. Donec pellentesque posuere tortor vel efficitur.
<p>
<p>Duis ligula purus, vulputate sed sodales quis, condimentum sit amet arcu. Sed fermentum ut dui ac posuere. Donec tristique volutpat lobortis. Aenean tortor elit, molestie nec tincidunt non, semper vel nisi. Phasellus quis est sit amet massa facilisis
posuere. Integer sit amet elit semper ipsum sodales tempus vitae id lacus. Donec facilisis libero sit amet aliquam fermentum. Sed luctus, tortor et ullamcorper faucibus, libero sem ornare tortor, at gravida erat lorem elementum eros.</p>
</div>
</div>

jQuery columnize crashes when setting height

I'm using the jquery columnizer plugin to create columns of a text in a div. The used plugin can be found here.
Below is an example of my html which should be divided into three columns:
<div class="textColumn">
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum adipiscing,
nisi tempus tincidunt tempor, lorem libero venenatis lectus, molestie congue arcu risus ut
lorem. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras mauris lorem, eleifend
vitae auctor id, rhoncus eget mi. Nunc convallis condimentum pretium. Praesent vulputate
mauris sit amet nisl porttitor fringilla. Aliquam sit amet venenatis risus. Nullam
malesuada hendrerit dolor, id sagittis libero condimentum non. Sed dapibus bibendum augue,
id lobortis arcu iaculis laoreet. Maecenas lacinia mattis ipsum, ut vehicula nulla
tristique id. Quisque vehicula orci vitae nibh ultricies ac dictum metus pretium. Donec id
arcu tellus, vulputate blandit augue. Integer turpis felis, cursus et congue sit amet,
mollis at neque. Nunc pellentesque erat vel odio tempus aliquam.<br>
<br>
Quisque faucibus lectus luctus odio blandit aliquet. Phasellus blandit augue vel eros
lacinia nec hendrerit ligula sagittis. Sed sollicitudin ultricies sem sit ametpellentesque.
Fusce semper purus vel massa porttitor vestibulum. Fusce eget erat eu augue ullamcorper
mattis. Morbi adipiscing fermentum purus, ut ultrices libero tristique sed. Fusce ut augue
in ante rhoncus iaculis. Nunc auctor, est sit amet ornare dictum, dolor odio elementum
orci, vitae porta enim nisi id felis. Aenean justo mauris, fringilla id faucibus eget,
tincidunt ornare purus. Aenean dapibus sapien non justo elementum sollicitudin. In at
vehicula turpis. Sed porta rhoncus arcu a cursus. Maecenas eu purus in urna mattis ornare
et et arcu. Suspendisse auctor magna ac tortor condimentum condimentum.<br>
</div>
</div>
In a generic javascript file i've defined a document.ready function in which in executing the columnizer to create my columns. This is done with the javascript below. It works fine when defining only a width. However, I also want to set a limited height for the columns. As soon as I do this the plugin (and there with also the browser) crashes.
$(document).ready(function(){
$('#content.one .textColumn .text').columnize({
width: 169
/*,height: 162*/ /*Enabling this rule crashes the internet!*/
});
});
I've tried with the width and height both setup, but also with only the height setup. Both make the plugin crash. Also defining the height inside the plugin (and therewith modifying the plugin) make it crash. According to this jquery plugin page it should be possible to set a height and also this example shows a working version.
Does anyone have a good resolution to this?
It is a bug in the plugin, please use this one:
https://raw.github.com/cioddi/Columnizer-jQuery-Plugin/71eae2c531419274a1ec085f6a6485038e98c9f3/src/jquery.columnizer.js
I got it from a git push request. Your js code is valid. please see this jsfiddle as prove:
http://jsfiddle.net/kxMJM/
I got the patched plugin from cioddi

Categories

Resources