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

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>

Related

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.

always make the expand button at the end of the paragraph

Here is the online sample: http://jsfiddle.net/Nh4K2/
<div class="container">
Nulla varius diam at sem adipiscing pharetra. Integer eget nulla non purus commodo aliquam. Aenean sed nunc neque. Aliquam eleifend aliquam arcu, ac semper nulla faucibus id. Etiam luctus eleifend tempus. Vestibulum ornare, nisi vitae fermentum luctus, sem lectus rhoncus nibh, auctor iaculis magna turpis nec turpis. Aliquam orci tortor, vulputate at pretium sit amet, blandit eget libero. Sed posuere ultricies mi, sed rhoncus massa ultrices quis. Donec pulvinar vestibulum rhoncus. Donec urna lacus, mollis et convallis at, commodo nec lectus. Maecenas pretium, nunc ac volutpat tempus, dolor orci ultricies massa, eu malesuada urna massa ut orci. Duis eget elit nulla, ornare aliquet nulla. Sed eleifend scelerisque est, eu laoreet lacus ultricies id. Aenean aliquam porttitor augue, quis lacinia augue consequat vitae. Ut venenatis orci massa. Duis dignissim, justo at pellentesque adipiscing, ligula eros mollis tellus, ut accumsan lorem dui eu est.
<div class="whatever">hahahahahaha</div>
<div class="damn">hohohohohohoho</div>
<div class="laugh">lololololololololo</div>
</div>
<span>Show</span>​
function excerpt(str, nwords) {
var words = str.split(' ');
words.splice(nwords, words.length - 1);
return words.join(' ') + '…';
}
var $div = $('.container');
$div.each(function() {
var theExcerpt = excerpt($(this).text(), 30);
$(this).data('html', $(this).html()).html( theExcerpt );
});
$('span').click(function() {
var isHidden = $(this).text() == 'Show';
var $div = $(this).prev();
var theExcerpt = excerpt($div.text(), 30);
$div.html( isHidden ? $div.data('html') : theExcerpt);
$(this).remove();
});​
any possible way to make "show" toggle button always shows at the end of the paragraph? rather than showing on the second line, the format looks like
Nulla varius diam at sem adipiscing pharetra. Integer eget nulla non
purus commodo aliquam. Aenean sed nunc neque. Aliquam eleifend aliquam
arcu, ac semper nulla faucibus…Show
Many thanks for any suggestions or solutions.
Add the span to the excerpt in the function.
Make sure you select the span's parent() instead of its prev().
http://jsfiddle.net/Nh4K2/3/
<div class="container">
Nulla varius diam at sem adipiscing pharetra. Integer eget nulla non purus commodo aliquam. Aenean sed nunc neque. Aliquam eleifend aliquam arcu, ac semper nulla faucibus id. Etiam luctus eleifend tempus. Vestibulum ornare, nisi vitae fermentum luctus, sem lectus rhoncus nibh, auctor iaculis magna turpis nec turpis. Aliquam orci tortor, vulputate at pretium sit amet, blandit eget libero. Sed posuere ultricies mi, sed rhoncus massa ultrices quis. Donec pulvinar vestibulum rhoncus. Donec urna lacus, mollis et convallis at, commodo nec lectus. Maecenas pretium, nunc ac volutpat tempus, dolor orci ultricies massa, eu malesuada urna massa ut orci. Duis eget elit nulla, ornare aliquet nulla. Sed eleifend scelerisque est, eu laoreet lacus ultricies id. Aenean aliquam porttitor augue, quis lacinia augue consequat vitae. Ut venenatis orci massa. Duis dignissim, justo at pellentesque adipiscing, ligula eros mollis tellus, ut accumsan lorem dui eu est.
<div class="whatever">hahahahahaha</div>
<div class="damn">hohohohohohoho</div>
<div class="laugh">lololololololololo</div>
</div>
​
function excerpt(str, nwords) {
var words = str.split(' ');
words.splice(nwords, words.length - 1);
return words.join(' ') + '…' + '<span>Show</span>';
}
var $div = $('.container');
$div.each(function() {
var theExcerpt = excerpt($(this).text(), 30);
$(this).data('html', $(this).html()).html( theExcerpt);
});
$('span').click(function() {
var isHidden = $(this).text() == 'Show';
var $div = $(this).parent();
var theExcerpt = excerpt($div.text(), 30);
$div.html( isHidden ? $div.data('html') : theExcerpt);
$(this).remove();
});​
You can simply set the display property of .container elements to inline.
Updated fiddle at http://jsfiddle.net/Nh4K2/2/
If you want them to be block, you could add a wrapper div around both .container and the <span>.
Your HTML is poorly structured, I would lay it out like this:
<div class="container">
<div class="description_text">
<span>description_text_here</span>
<span class="show_more"> Show</span>
</div>
<div class="more_text_to_show">
<p>more_text_to_show_here</p>
</div>
</div>
At least that is what I am reading into your question and posted code.

jQuery height() returning no value

I want to make an scrollable div that scrolls down when the user hovers another div. The content inside the scrollable div will change (it's gonna be only text) so I can't set up an absolute height value for that DIV, this is why div's height is 'auto'.
I have come into a solution that works when I set up an absolut height value on '.post-right' div's CSS, but it returns no value if div's height is 'auto' just I like I need it to be.
I've tried putting jQuery block of code on the (document).ready function as well, result is exactly the same.
Any ideas? Thank's in advance.
HTML CODE:
<div class="post-right-cont">
<div class="post-right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut aliquam libero ut nisi consectetur pretium. Donec auctor auctor mauris, in tempor mauris blandit et. Aliquam nibh felis, tincidunt a auctor vel, feugiat at enim. Duis faucibus porta mi ut fringilla. Pellentesque eleifend erat a tellus aliquam sodales. Nullam lorem tellus, accumsan quis laoreet id, luctus et urna. Curabitur eleifend tellus non orci ullamcorper adipiscing. Integer est tellus, bibendum at ultricies a, viverra at orci. Curabitur porta tincidunt nunc, at placerat ipsum malesuada et. Vivamus et est purus, id suscipit tortor. Curabitur turpis metus, dapibus et consectetur non, tincidunt in est. Vestibulum nisl libero, sodales sit amet auctor eu, congue at velit. Vivamus et erat massa, nec viverra risus. Fusce iaculis dolor vel augue ornare accumsan.<br/><br/>
Quisque a metus arcu. Suspendisse hendrerit commodo justo in sagittis. Phasellus a scelerisque quam. Fusce lacinia lacinia justo. Duis id hendrerit enim. Sed eleifend eros et turpis rutrum consectetur. Maecenas pulvinar volutpat odio, non imperdiet augue pretium quis. Proin rutrum, est vitae auctor dapibus, diam dolor rutrum libero, sed feugiat metus turpis sed mauris. Sed eleifend dolor arcu. Cras laoreet nibh convallis magna congue sit amet consequat tortor porttitor. Duis et mauris non lorem consectetur luctus. Aliquam mollis sem sit amet tortor iaculis egestas. Duis tincidunt pellentesque leo, nec vulputate turpis dapibus sit amet. Aliquam rhoncus luctus orci, et aliquet eros porttitor in. Etiam arcu eros, viverra tristique tincidunt vel, facilisis et mauris.<br/><br/>
Morbi congue auctor luctus. Sed nisl dui, varius id ornare et, tincidunt sit amet enim. Aliquam egestas ultricies nisl, id condimentum erat fermentum quis. Morbi lectus nunc, aliquam volutpat egestas quis, iaculis a nulla. Pellentesque fermentum mauris at libero pulvinar viverra. Aliquam a ante orci, a luctus purus. Vivamus ut est ut mauris pulvinar mattis ac et magna. Aenean congue dictum lectus at suscipit. Suspendisse interdum, erat pulvinar gravida vulputate, mi mauris feugiat justo, at euismod augue sapien eu sapien. Praesent at quam purus. In hac habitasse platea dictumst. Fusce vel tellus a massa tempor volutpat a at magna. In eu enim odio. Quisque bibendum tortor est. Phasellus a scelerisque quam. Fusce lacinia lacinia justo. Duis id hendrerit enim. Sed eleifend eros et turpis rutrum consectetur. Maecenas pulvinar volutpat odio, non imperdiet augue pretium quis. Proin rutrum, est vitae auctor dapibus, diam dolor rutrum libero, sed feugiat metus turpis sed mauris. Sed eleifend dolor arcu.
</div>
<div class="scroll-down"></div>
<div class="scroll-up"></div>
</div>
CSS:
.post-right-cont {
width: 540px;
height: auto;
overflow: hidden;
position: relative;
}
.post-right {
position: absolute;
top: 0;
left: 20px;
height: auto;
width: 480px;
padding-top: 40px;
}
jQuery:
$(window).load(function() {
// SCROLL POST
// EDIT - post-right-cont height was set up before. I just past it here now.
var wHeight = $(window).height();
$('.post-right-cont').css('height', wHeight - 36);
if ($('div.post-right').height() > $('.post-right-cont').height()) {
$('div.scroll-down').hover(function() {animateContent('down');}, function() {
$('div.post-right').stop();
});
$('div.scroll-up').hover(function() {animateContent('up');}, function() {
$('div.post-right').stop();
});
}
function animateContent(direction) {
var containerHeight = $('.post-right-cont').height();
var textHeight = $('div.post-right').height();
var animationOffset = textHeight - containerHeight;
if (direction == "up") {
animationOffset = 0;
}
$('div.post-right').animate({"top" : -animationOffset + "px" }, 8500);
}
});
$('.post-right-cont').height() will return a value 0 because you have wrapped just one item inside, which have absolute positioning, so the absolute positioned element will not increase the size of .post-right-cont. So jQuery returns the correct value - 0. The height of .post-right will not increase the height of .post-right-cont because absolute positioned elements do not increase the height or width of their wrapping tag.

jQuery/JavaScript - auto cut & format paragraphs depending on the browser's window height and width

Let say I have a very long page of content consisting of multiple paragraphs which cannot be
displayed in a single browser window with vertical scrollbar
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
So I want to cut the paragraphs and format them into multiple pages, e.g.
<!-- page 1 -->
<p>...very long sentence ...</p>
<p>...very long </p><!-- the ending p tag is automatic inserted since the following text cannot be displayed -->
<!-- page 2 -->
<p>sentence ...</p>
<p>...very long sentence ...</p>
<p>...very long sentence ...</p>
Are there any existing scripts for this purpose?
In the extreme case the paragraph might contain image, so each line might be variying in height.
Someone has created show/hide functionality with jQuery.
This may help you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example: Show more, less using jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<style type="text/css">
a.moreText
{
color: blue;
cursor: pointer;
padding-left: 5px;
padding-right: 10px;
}
a.lessText
{
cursor: pointer;
color: blue;
display: none;
padding-left: 5px;
padding-right: 10px;
}
span.secondHalf
{
display: none;
}
</style>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("p").each(function () {
SetMoreLess(this, 350, 20, " ... more", " ... less");
});
$("a.moreText").click(function () {
$(this).hide();
var pTag = $(this).parents("p.summary");
$(pTag).find("a.lessText").show();
$(pTag).find("span.secondHalf").show();
});
$("a.lessText").click(function () {
$(this).hide();
var pTag = $(this).parents("p.summary");
$(pTag).find("a.moreText").show();
$(pTag).find("span.secondHalf").hide();
});
});
function SetMoreLess(para, thrLength, tolerance, moreText, lessText) {
var alltext = $(para).html().trim();
$(para).addClass("summary"); // this class is added to identify the p tag, when more/less links are clicked
if (alltext.length + tolerance < thrLength) {
return;
}
else {
var firstHalf = alltext.substring(0, thrLength);
var secondHalf = alltext.substring(thrLength, alltext.length);
var firstHalfSpan = '<span class="firstHalf">' + firstHalf + '</span>';
var secondHalfSpan = '<span class="secondHalf">' + secondHalf + '</span>';
var moreTextA = '<a class="moreText">' + moreText + '</a>';
var lessTextA = '<a class="lessText">' + lessText + '</a>';
var newHtml = firstHalfSpan + moreTextA + secondHalfSpan + lessTextA;
$(para).html(newHtml);
}
}
</script>
</head>
<body>
<div id="lipsum">
<p>
Integer consectetur, dui ut lobortis aliquet, leo est ullamcorper augue, id blandit
metus libero eu leo. Pellentesque dui sapien, tempus ultricies ultricies nec, molestie
at eros. Integer facilisis luctus libero quis accumsan. Suspendisse eu velit ac
erat iaculis pellentesque vel mollis est. Cras ac erat vulputate augue tincidunt
euismod a eu diam. Pellentesque habitant morbi tristique senectus et netus et malesuada
fames ac turpis egestas. Nullam sed arcu lorem. Cras porta dui in lorem tempor dapibus.
Ut magna metus, tincidunt et sodales pretium, aliquam ac ligula. Etiam at enim id
enim rhoncus scelerisque. Fusce porta, arcu non malesuada consequat, massa lectus
feugiat diam, aliquam convallis neque mauris eu urna. Nulla pellentesque eleifend
lectus, vel sodales leo consequat vestibulum. Sed elementum, lorem ac mollis mattis,
purus dolor interdum neque, ac rutrum nisl elit eu arcu. Curabitur risus arcu, suscipit
dignissim hendrerit at, luctus nec mauris. Pellentesque accumsan euismod sem nec
feugiat. Nullam faucibus gravida elit, nec facilisis lorem ullamcorper nec.
</p>
<p>
Vestibulum tincidunt lacus sit amet justo blandit vehicula. In pretium sem quis
ligula ultricies eget sodales velit mollis. Phasellus facilisis varius enim, non
rutrum nulla scelerisque eu. Curabitur posuere quam eget dui dignissim sed placerat
ante tincidunt. Suspendisse faucibus vulputate est quis feugiat. Nulla nec ante
a enim molestie consectetur. In hac habitasse platea dictumst. Donec tincidunt lacinia
pellentesque. Integer hendrerit ligula non nibh posuere pretium. Sed tincidunt tincidunt
lectus, non consectetur est iaculis sit amet. Morbi vel lobortis ligula. Sed scelerisque
varius interdum. In sollicitudin lorem et mauris luctus venenatis commodo nunc venenatis.
Praesent vitae justo nisl.
</p>
<p>
Nulla posuere ante vel quam dapibus fringilla. In elementum mi interdum nisl vehicula
eu iaculis felis pretium. Ut id massa eget turpis gravida luctus et non nunc. Etiam
viverra suscipit mauris quis scelerisque. Vestibulum tempor neque nisl, nec aliquam
nibh. Quisque cursus faucibus libero sit amet placerat. Nulla id blandit ligula.
Nullam aliquam dui at justo facilisis accumsan. Morbi vel arcu id mi mollis vestibulum.
Praesent imperdiet, lectus eget adipiscing lobortis, urna enim vulputate lorem,
et bibendum turpis arcu quis ligula. Donec ultricies sollicitudin imperdiet. Mauris
a augue nulla. Donec sagittis est magna, sed scelerisque magna. Nam tincidunt, felis
quis luctus sodales, orci ligula consequat massa, a pulvinar leo urna id dui. In
sit amet augue est, et tincidunt metus. Quisque pellentesque, felis vel semper ullamcorper,
leo nulla eleifend nunc, et suscipit massa tellus non tellus.
</p>
<p>
Etiam accumsan, diam semper mattis tempus, sapien erat cursus dui, venenatis convallis
metus lectus at arcu. Duis eget dolor nec metus laoreet aliquam. Nulla eu viverra
massa. Vestibulum id urna ante, at aliquam augue. Cum sociis natoque penatibus et
magnis dis parturient montes, nascetur ridiculus mus. Nulla risus felis, convallis
at sagittis nec, fringilla in lacus. Integer at fermentum enim. Nullam lacinia eleifend
nisi, laoreet porta nunc elementum ut. Nulla facilisi.
</p>
<p>
Fusce id orci dui. In nec tempor nulla. Fusce commodo cursus orci in feugiat. Fusce
porttitor nulla sit amet arcu tempor nec viverra risus tempor. Pellentesque felis
lectus, pellentesque dignissim interdum sed, aliquam eu urna. In molestie leo vel
massa dapibus imperdiet. Ut risus odio, rutrum eu congue sit amet, pellentesque
quis urna. Duis tempor magna eu nisl volutpat eget pulvinar ante rutrum. Morbi quis
dolor lorem, sit amet pellentesque mauris. Nunc tellus tellus, consequat a pharetra
eu, cursus eu dolor. Aliquam non dolor mauris. Vestibulum vel purus eu massa sollicitudin
sollicitudin vel in mauris. Proin tristique, mi sed tempus facilisis, odio elit
faucibus turpis, sed aliquam risus elit in urna.
</p>
<p>
Suspendisse et libero tincidunt mauris pharetra hendrerit at ac nisl. Cras mauris
ante, sodales at scelerisque in, ullamcorper sed ipsum. Praesent est erat, mollis
eget ullamcorper quis, mattis ac nisi. Pellentesque habitant morbi tristique senectus
et netus et malesuada fames ac turpis egestas. Etiam vulputate, lacus non iaculis
euismod, urna eros fringilla leo, a faucibus enim metus sed nibh. Etiam sagittis
sodales porttitor. Aliquam consequat lacus sed enim scelerisque vel malesuada sapien
viverra. Nulla massa metus, dignissim at consectetur sed, elementum nec massa. Phasellus
cursus, odio sagittis molestie aliquam, est mi volutpat nibh, nec ullamcorper lacus
mi sit amet nulla. Vivamus pellentesque, nulla ut pretium pretium, massa justo malesuada
nibh, a adipiscing diam enim eget elit. Phasellus nec sapien id elit lobortis sodales
vel ut neque. Sed ultricies tincidunt hendrerit. Vestibulum at velit diam, in sollicitudin
eros. Cras tincidunt tincidunt orci, id hendrerit lorem porttitor a.
</p>
<p>
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
mus. Ut tortor quam, sodales a egestas ac, consectetur vitae eros. Suspendisse sit
amet libero ac magna sagittis tincidunt. Quisque a risus orci. Etiam nec velit tortor,
sed interdum nulla. Mauris nec lorem tortor, a dapibus mi. Sed posuere tempor magna
vitae consequat.
</p>
<p>
Nam ornare massa a velit congue ut con</p>
<p>
Nulla sed magna sed lectus imperdiet sagittis sed at nunc. Duis ornare tortor in
eros rhoncus quis tempor justo congue. Proin ut suscipit augue. Sed consectetur
arcu eget purus condimentum venenatis. Pellentesque dui orci, malesuada ut fringilla
et, tincidunt quis est. Pellentesque ipsum metus, pulvinar sit amet accumsan non,
imperdiet non enim. Donec leo lorem, pharetra at eleifend id, malesuada ut enim.
Proin ligula risus, pretium eget adipiscing a, sagittis et tellus. Duis dictum tristique
pretium. Sed mattis neque vitae augue aliquet dictum. Proin ut tempus velit. Donec
tincidunt hendrerit risus, vel imperdiet libero interdum ut. Phasellus rutrum sem
a urna semper et fermentum purus mattis. Aliquam euismod tempor dapibus. Maecenas
ultrices magna at ligula ultrices at accumsan erat sagittis. Ut neque ante, scelerisque
ut laoreet egestas, tempus ut erat.
</p>
</div>
</body>
</html>
In case of paragraph with image and other html tags use below logic:
<div style="height:500px;overflow:hidden" id="blah">
Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.Hello Hello Hello.
</div>
Show more
<script>
$("#showmore").live('click', function() {
$("#blah").css('height','1000px');
});
</script>
Edited: (Demo Link Updated)
See this DEMO
By using the below code you can paginate limitless paragraphs as according to your need.
jQuery:
$(document).ready(function(){
//how much items per page to show
var show_per_page = 5;
//getting the amount of elements inside content div
var number_of_items = $('#content').children().size();
//calculate the number of pages we are going to have
var number_of_pages = Math.ceil(number_of_items/show_per_page);
//set the value of our hidden input fields
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
//now when we got all we need for the navigation let's make it '
/*
what are we going to have in the navigation?
- link to previous page
- links to specific pages
- link to next page
*/
var navigation_html = '<a class="previous_link" href="javascript:previous();">Prev</a>';
var current_link = 0;
while(number_of_pages > current_link){
navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
current_link++;
}
navigation_html += '<a class="next_link" href="javascript:next();">Next</a>';
$('#page_navigation').html(navigation_html);
//add active_page class to the first page link
$('#page_navigation .page_link:first').addClass('active_page');
//hide all the elements inside content div
$('#content').children().css('display', 'none');
//and show the first n (show_per_page) elements
$('#content').children().slice(0, show_per_page).css('display', 'block');
});​
function previous(){
new_page = parseInt($('#current_page').val()) - 1;
//if there is an item before the current active link run the function
if($('.active_page').prev('.page_link').length==true){
go_to_page(new_page);
}
}
function next(){
new_page = parseInt($('#current_page').val()) + 1;
//if there is an item after the current active link run the function
if($('.active_page').next('.page_link').length==true){
go_to_page(new_page);
}
}
function go_to_page(page_num){
//get the number of items shown per page
var show_per_page = parseInt($('#show_per_page').val());
//get the element number where to start the slice from
start_from = page_num * show_per_page;
//get the element number where to end the slice
end_on = start_from + show_per_page;
//hide all children elements of content div, get specific items and show them
$('#content').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');
/*get the page link that has longdesc attribute of the current page and add active_page class to it
and remove that class from previously active page link*/
$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');
//update the current page input field
$('#current_page').val(page_num);
}
HTML:
<!-- the input fields that will hold the variables we will use -->
<input type='hidden' id='current_page' />
<input type='hidden' id='show_per_page' />
<!-- Content div. The child elements will be used for paginating(they don't have to be all the same,
you can use divs, paragraphs, spans, or whatever you like mixed together). '-->
<div id='content'>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>
<p>and so on....</p>
</div>
<!-- An empty div which will be populated using jQuery -->
<div id='page_navigation'></div>
A while ago, I created pagify, a jQuery plugin to do just that. It detects page height by splitting elements into words and incrementally adding the words until the height reaches a specified height. I've given it some CSS to make it look like pages in the demo below, but you can style it to use 100% width and height. You can call it simply with $('body').pagify(options); The default options are as follows
{
'pageTag' : 'div', // the tag which surrounds each page
'pageClass': 'page', // the class of the page tag
'innerClass': 'page-inner', // the class of the inner page element
'pageSize': 'A4', // a class added to the page so that the size can be defined by css
'pageSizeClassPrefix': 'page-', // the prefix to the above class
'pageOrientation': 'portrait', // not yet used, but could be used to flip width and height
'splitElementClass': 'split-element' // elements which have been split across two pages are given this class
};
So to use 100% width and height:
html, body, page-screen-size {
width: 100%;
height: 100%;
}
and
$('body').pagify({
pageSize : 'screen-size'
});
Here it is in action: http://jsfiddle.net/nathan/nfHHE/
From what I understand this is very similar to the way an online reader works, where content is formatted into different pages or slides and it doesn't matter what the content inside it is, as this will adapt to its container.
In order to achieve your goal, I'd recommend CSS3 Multi-column layout (see http://www.w3.org/TR/2001/WD-css3-multicol-20010118/)
CSS
#your-container
{
width: 90%;
margin: 0 auto;
overflow: hidden; //Hide overflowing content
padding: 20px 0;
}
#div-inside-container //For padding and columns display purposes
{
position: relative;
-moz-column-count: 1;
-webkit-column-count: 1;
column-count: 1;
-moz-column-width: 50em;
-webkit-column-width: 50em;
column-width: 50em;
-webkit-column-gap: 0;
-moz-column-gap: 0;
column-gap: 0;
}
JQUERY
$(window).resize(function() {
//Resize container
$(div_content).height(Dimensions.TellMeHeight() - padding);
});
See example and code: http://jsfiddle.net/GLbXX/1/
you can use jquery accordion control, if you have multiple paragaraphs than you should divide then in accordion, it will improve the readabilty and look of your page
Read more from here
The Financial Times has developed a JavaScript solution for multi-column layout with special focus on complicated (i.e. newspaper-like) cases, FTColumnFlow.
If you set a container to the width of one column and do then some pagination, i.e. via jQuery UI tabs, this might be a solution, that caters most difficult cases.
I hope this code help you. Maybe there is some cases which are omitted or you can find a better alhorithm or you can optimize it. It is just a way to lead you.
$(document).ready(function(){
var current_page_height = $(window).innerHeight() - $("div.pagination").innerHeight();
function createPages(page_height){
var current_page_height = 0;
var pages = [];
var current_page = [];
var cpt_page = 0;
$("div.content").children().each(function(index, element){
var el = $(element);
el.hide();
if(current_page_height + el.innerHeight() > page_height){
var height_over = (current_page_height+el.innerHeight()) - page_height;
var line_height_el = el.css("line-height").replace("px","")
if( line_height_el < height_over && el.find("img").length == 0){
var number_line_to_remove = Math.round(height_over/line_height_el);
var number_line = el.innerHeight() / line_height_el;
var char_by_line = Math.floor(el.html().length / number_line);
var content_el = el.html();
var pointer_substr = (number_line - number_line_to_remove) * char_by_line;
while(content_el.charAt(pointer_substr) != " " && pointer_substr > 0){
pointer_substr--;
}
var new_element = $("<p>" + content_el.substr( pointer_substr, content_el.length-1) + "</p>");
el.html( content_el.substr(0, pointer_substr+1));
current_page.push(el);
el.after(new_element);
el = new_element;
el.hide();
}
pages[cpt_page] = current_page;
current_page_height = 0;
current_page = [];
cpt_page++;
}
current_page.push( el );
current_page_height += el.innerHeight();
});
if(current_page.length > 0){
pages[cpt_page] = current_page;
}
return pages;
}
function displayPage(page_to_display){
if( page_to_display >= 0 && page_to_display < pages.length){
$(pages[page_to_display]).each(function(index, element){
element.show();
});
$(pages[$("span.page").html()]).each(function(index,element){
element.hide();
});
$("span.page").html(page_to_display);
}
}
var pages = createPages(current_page_height);
displayPage(0);
$("span.next").click(function(){
var page = new Number($("span.page").html());
displayPage( page+1 );
});
$("span.prev").click(function(){
var page = new Number($("span.page").html());
displayPage( page-1 );
});
});
You can find an example here
Sugar.js has a great .truncate() function that crops text to your specifications
http://sugarjs.com/api/String/truncate
try this jquery plugin
jqPagination or jPaginate
have a look at :before and :after pseudo-elements in CSS (sorry, I can't be more specific, I'm still on the discovery path myself)

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