Scroll fixed content with jQuery - javascript

I am using jQuery to detect which div is bigger out of two columns. The smaller div gets a class of .js-small-content. That class has a position:fixed on it.
However the issue that I am having is that I need to be able to scroll the fixed content. Which I understand sounds weird as why would I want to scroll something thats fixed?
If you take a look at my jsFiddle you will see that I need to be able to scroll the cat content so I can see all the images.
This is an example of the effect that I am after. You can see that the small content allows you to scroll it first and then once it has all been viewed it then fixes to the bottom of the content and continues scrolling the images on the left.
I think I may need to do something with the viewport on scroll but I'm not sure how to achieve this?
Here is my code:
var a = document.querySelector('#single__images');
var b = document.querySelector('#single__content');
var aH = a.scrollHeight;
var bH = b.scrollHeight;
(aH > bH ? b.classList.add("js-small-content") : a.classList.add("js-small-content"));
HTML:
<article>
<div id="single__image"><img src="#"/></div>
<div id="single__content">Text goes here</div>
</article>

I have worked really long for this, as was challenging for me. Finally made it.
According to you, you want to add class and remove class to smaller one among two div's. Which i have accomplished(but its' not right way to do at all) with my own other way.
I have made the smaller div to stop scroll when reaches at three fourth of window position from top.
JSFiddle : Demo
$(window).scroll(function()
{
var divImg = document.getElementById("single__images").id;
var divCont = document.getElementById("single__content").id;
// Height of single__content
var hC = $("#" + divCont).outerHeight();
// Height of single__images
var hI = $("#" + divImg).outerHeight();
// Check out the smaller one
if(hC<hI)
{
var samllOne = document.getElementById("single__content").id;
}
else
{
var samllOne = document.getElementById("single__images").id;
}
// Height of Smaller Div
var h = $("#" + samllOne).outerHeight();
// Position of Smaller Div from top
var topPos = $("#" + samllOne).position();
var topPos = topPos.top;
// Height of Smaller Div
var h = $("#" + samllOne).outerHeight();
// Div Height + TOP Space from from Body
var bottomCont = topPos + h;
// Checks current Scroll
var curScroll = $(this).scrollTop();
var windowH = $(window).innerHeight();
var windowMid = windowH / 2;
var midOfMid = windowMid / 2;
var threeFourth = windowMid + midOfMid;
var bottomTouch = h - threeFourth;
if(curScroll >= bottomTouch)
{
$("#" + samllOne).css({position: "fixed", top: "-" + bottomTouch + "px" });
}
else
{
$("#" + samllOne).css({position: "relative", top: "0px" });
}
});
article {
position:relative;
}
#single__images {
float:left;
width:200px;
}
img {
max-width:100%;
width:100%;
}
#single__content {
float:right;
width:200px;
right:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<article>
<div id="single__images">
<div class="inner">
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
</div>
</div>
<div id="single__content">
<div class="inner">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin commodo sed libero non lobortis. Aliquam aliquam vulputate felis. Phasellus hendrerit tellus ut libero bibendum rhoncus. Cras et ultricies neque. Curabitur posuere leo scelerisque mattis semper. In et arcu dictum, dictum libero ac, blandit nibh. Ut pharetra velit non blandit pretium. Suspendisse malesuada sodales orci, nec interdum ligula vestibulum ut. Mauris libero massa, tempus vel eleifend sit amet, efficitur nec sem.
Vivamus pretium malesuada ligula quis pulvinar. Duis ornare at massa et elementum. In ac consectetur turpis. Duis in velit nec nunc feugiat semper at in augue. Praesent ut odio quam. Ut faucibus eget massa a suscipit. Mauris fermentum est sed hendrerit lacinia. Mauris ac eleifend dolor. Phasellus rutrum volutpat efficitur. Maecenas vestibulum auctor massa, non dapibus diam laoreet id. Curabitur tincidunt massa vitae nibh varius iaculis. Duis sit amet nisi tempor, vestibulum ipsum at, rutrum purus. Mauris accumsan vulputate convallis. Morbi hendrerit ultrices erat, eu mollis neque faucibus id. Fusce sed magna semper justo placerat placerat quis eget augue.
Phasellus fermentum laoreet felis nec efficitur. Donec ultrices rutrum auctor. Duis faucibus rutrum tortor, ut eleifend libero pellentesque vitae. In nec ullamcorper justo. Donec eget aliquam est. Phasellus semper aliquam odio eu interdum. Praesent ultricies lectus nibh, ac bibendum lacus tempor sed. In ac ultrices sapien, vitae iaculis diam. Nullam pharetra lacus quis facilisis finibus. In a nisl aliquam, viverra dolor quis, auctor metus. Cras nec euismod nulla.
Duis sed ultrices erat. Sed semper lorem vel turpis aliquam vulputate. Nam ornare mauris a lorem posuere, id ultrices erat fringilla. Morbi eget posuere felis. Donec semper odio vitae porta bibendum. Duis sit amet metus at ligula iaculis pretium. Quisque at consectetur tortor. Etiam nec nisi porttitor, dignissim odio quis, condimentum risus. Quisque ipsum ipsum, pulvinar vel mi non, semper fringilla lacus. Mauris vestibulum mauris semper mauris venenatis, vitae suscipit dolor tincidunt. Aliquam eget mi lacus.
Nullam hendrerit sem ligula, sit amet malesuada ipsum rhoncus ut. Aenean urna nisl, finibus at arcu a, posuere aliquet odio. Fusce mollis dapibus leo, non aliquam tellus facilisis sit amet. Nunc commodo mauris eu gravida vehicula. Vestibulum sagittis magna orci, in tempus urna lacinia ut. Suspendisse potenti. Pellentesque ultrices, tellus sed laoreet tincidunt, urna mi facilisis sapien, a pretium lacus leo vitae elit.
</div>
</div>
</article>

I updated your JSFiddle project.
I just added the following to your CSS file. Hope this helps and is kind of self explaining.
.js-small-content {
position:absolute;
overflow-y:scroll;
overflow-x:hidden;
height:130px;
}

Related

Viewheight on Chrome Mobile

I have a popup window, that is a div. It shouldn't go out of the screen, so I added an other div that is scrollable to facilitate the content if it's longer than the screen height. I can set the inner divs max-height in javascript like this (because I have content before it, so I don't know where it starts.):
var rect = container.getBoundingClientRect();
container.style.maxHeight = "calc(100vh - " + rect.top + "px - 15vh)";
This approach works on computers, but on smartphones in Chrome, the viewheight is more than what the user actually sees, because the url bar takes up space, so when that bar is shown, the end of the div is out of the screen. So how can I make the div end "15vh" from the actual bottom of the screen.
My code:
var container = document.getElementById("container");
var rect = container.getBoundingClientRect();
container.style.maxHeight = "calc(100vh - " + rect.top + "px - 15vh)";
body {
background-color: black;
}
#popup_content {
position: relative;
margin: auto;
background-color: red;
width: 80%;
max-width: 500px;
}
#container {
overflow: auto;
max-height: 50vh;
}
<div id="popup_content">
<p>some content</p>
<div id="container">
A lot of text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tempus, est vel congue eleifend, ante tortor ultricies leo, eu consectetur magna odio ac nibh. Nulla laoreet odio dui, ac aliquet purus porttitor et. Aliquam blandit vestibulum mauris, vel eleifend diam ultrices in. Vivamus eget eleifend dui. Cras aliquet libero et lorem venenatis ultricies. Vestibulum pulvinar erat eget velit porta, a gravida nunc scelerisque. Aliquam ut varius nibh. Aenean volutpat imperdiet nibh quis vestibulum. Donec eget magna varius, tempus augue ac, auctor ipsum. Vivamus quis egestas mauris. Vivamus dapibus risus hendrerit viverra ullamcorper. Pellentesque sodales elementum leo, sit amet ultricies elit rhoncus eu. Phasellus consectetur sit amet sem at mattis. Aliquam finibus risus ut ante pharetra, ut condimentum ligula convallis. Maecenas hendrerit, ligula at finibus pellentesque, justo ante varius metus, a luctus libero dui ut risus. Pellentesque dictum, risus ut fermentum tincidunt, purus massa dictum lectus, id aliquam neque risus at augue. Phasellus laoreet fermentum elementum. Donec sit amet aliquam neque. In consequat nec augue aliquam congue. Suspendisse purus neque, luctus vel placerat sed, pellentesque eget neque. Morbi tincidunt iaculis neque in imperdiet. Donec id tortor nunc. In lacinia rhoncus lectus, vitae feugiat felis egestas at.
</div>
</div>

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 - trimming image to remove div

i am trying through jquery to remove a div completely when there is no child element within it. The variable I am using is an image. I can't seem to select the variable as an image, i only know how to do this through text. Could someone please help me and resolve this issue, so it detects that there is a img contained within the div and displays it and when there isn't an image it doesn't display it.
I have uploaded it through jsfiddle:http://jsfiddle.net/cLkFD/
<div class="content-container"><!--content-container-->
<h3>title</h3>
<div class="picture"><!--picture-->
<img src="images/buddha.jpg" width="981" height="324" alt=""/>
</div><!--/picture-->
<div class="content"><!--content-->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et cursus neque, sit amet blandit tellus. Cras leo mauris, laoreet quis consequat et, pharetra mattis risus. Duis tortor lorem, ultrices egestas arcu sed, pretium egestas est. Morbi condimentum sem quis tortor placerat iaculis. Ut nisl augue, rutrum sed sem et, blandit hendrerit nibh. Donec et rhoncus odio, id tempor enim. Praesent ultricies justo vulputate dui gravida fermentum. Pellentesque id aliquet leo. Quisque vulputate, dolor vel rutrum accumsan, turpis odio faucibus sem, vel malesuada eros turpis ac magna. Nullam fermentum vehicula odio, ut ornare justo varius nec. Morbi lectus leo, porttitor nec elementum at, suscipit aliquam nunc. Ut gravida a sem ut imperdiet. Duis et turpis eget magna lobortis accumsan. In ac tincidunt nibh, quis pulvinar risus.
</p>
<button class="btn btn-1 btn-1a">Read More</button>
</div><!--content-->
</div><!--content-container-->
(function($) {
$.fn.equalHeights = function(minHeight, maxHeight) {
tallest = (minHeight) ? minHeight : 0;
this.each(function() {
if($(this).height() > tallest) {
tallest = $(this).height();
}
});
if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
return this.each(function() {
$(this).height(tallest).css("overflow","hidden");
});
}
})(jQuery);
You can check to see whether any image inside your div or not using length:
$(function () {
$('.picture').each(function () {
if ($(this).find('img').length) {
$(this).hide();
}
});
});
http://jsfiddle.net/9VBJP/
The above fiddle should work
$('.picture').each(function(){
var imageElem = $(this).find('img');
if(imageElem.length == 0) {
$(this).hide();
}
});

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)

Categories

Resources