Exclude element from jquery animation - javascript

I am almost positive that this question has been answered before, but the reason that I am asking this question is because I am not sure how to implement the answers into my code without breaking it. I have an accordion menu and it utilizes headers, paragraph tags, divs for the structure of the accordion. Well what I am trying to do is use a div inside of the accordion to display images, but here is the thing: divs are used for the structure of the accordion.
So, what I am asking is how to have jQuery treat this div as purely
content and not part of the structure?
I am pretty sure that the answer is to use .not(), but not sure. I only understand the basics when it comes to JavaScript and jQuery. I am really sorry for this guys... I am the type of person that learns by doing, not by reading a book.
var headers = ["H1", "H2", "H3", "H4", "H5", "H6"];
$(".accordion").click(function(e) {
var target = e.target,
name = target.nodeName.toUpperCase();
if ($.inArray(name, headers) > -1) {
var subItem = $(target).next();
//slideUp all elements (except target) at current depth or greater
var depth = $(subItem).parents().length;
var allAtDepth = $(".accordion p, .accordion div:not(.exclude)").filter(function() {
if ($(this).parents().length >= depth && this !== subItem.get(0)) {
return true;
}
});
$(allAtDepth).slideUp("fast");
//slideToggle target content and adjust bottom border if necessary
subItem.slideToggle("fast", function() {
$(".accordion :visible:last").css("border-radius", "0 0 10px 10px");
});
$(target).css({
"border-bottom-right-radius": "0",
"border-bottom-left-radius": "0"
});
}
});
<aside class="accordion">
<div class="opened-for-codepen">
<h2>How do I recruit members?</h2>
<div class="exclude image_legend">
<span>Image legend for "How do I recruit members?" section</span>
<br />
<br />
<img src="includes/images/clan/clan-tab.png" height="40px" style="display: inline;" />
<img src="includes/images/clan/clan-bottom-bar.png" height="40px" style="display: inline\;" />
<img src="includes/images/clan/clan-recruit.png" height="40px" style="display: inline-block;" />
<img src="includes/images/clan/clan-tab.png" height="40px" style="display: inline-block;" />
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis arcu augue. Donec varius semper interdum. Sed condimentum ipsum enim, a egestas nunc blandit a. Aenean varius dapibus suscipit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Quisque et lectus sapien. Nulla dapibus porta libero ac efficitur. Phasellus condimentum ornare porta. Aliquam erat volutpat. Nullam nec orci vitae felis mattis suscipit consectetur sit amet urna. Nulla lobortis augue ac commodo condimentum. Maecenas
ac dui cursus, congue felis quis, varius elit. Curabitur nulla lacus, dignissim ut pellentesque at, posuere sit amet eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec nec sapien diam. Nulla
accumsan viverra tellus sed laoreet. In eleifend nulla libero, vehicula consectetur magna condimentum vitae. Suspendisse non rhoncus justo. Nullam eleifend elit nec neque efficitur, quis fermentum metus pretium. Quisque tellus mauris, molestie in
ultrices eu, tincidunt ut nibh. Fusce eu volutpat felis. Integer ligula nulla, mattis quis pulvinar pharetra, vehicula nec arcu. Vivamus tincidunt nulla a nisi vehicula lobortis. In hendrerit, neque quis convallis lacinia, nisl ipsum varius lorem,
nec laoreet nisi odio vitae est. Nulla vitae diam enim. Suspendisse a dignissim magna. Pellentesque convallis maximus mollis. Nullam tellus est, accumsan sit amet facilisis sit amet, semper sed lorem. Mauris laoreet tortor at odio aliquet, ut porta
lacus rhoncus. Nullam laoreet dolor et velit malesuada feugiat. Vestibulum a erat elementum, hendrerit massa non, ornare enim. Phasellus iaculis diam eros, sit amet dapibus elit finibus id.
</p>
</div>
</aside>
Edit: The above html is consolidated because there is a lot of content to include all of it, but I provide you with the basic structure that makes the accordion

Assign a class to your div (Ex. 'my-class')
Then use not :not() to filter the selection
var headers = ["H1","H2","H3","H4","H5","H6"];
$(".accordion").click(function(e) {
var target = e.target,
name = target.nodeName.toUpperCase();
if($.inArray(name,headers) > -1) {
var subItem = $(target).next();
//slideUp all elements (except target) at current depth or greater
var depth = $(subItem).parents().length;
var allAtDepth = $(".accordion p, .accordion div:not(.my-class)").filter(function() {
if($(this).parents().length >= depth && this !== subItem.get(0)) {
return true;
}
});
$(allAtDepth).slideUp("fast");
//slideToggle target content and adjust bottom border if necessary
subItem.slideToggle("fast",function() {
$(".accordion :visible:last").css("border-radius","0 0 10px 10px");
});
$(target).css({"border-bottom-right-radius":"0", "border-bottom-left-radius":"0"});
}
});

Related

Position an element relative to another that is not its parent

Considering that components such as dialogs, modals, tooltips, etc. should be of higher stacking index than any other elements in an HTML page, I placed these components in an immediate sibling of root element where all the other elements are placed. React developers will quickly recognize this and they'll know that I'm trying to use React Portals. You can visualize it here:
<body>
<div id="root">
// ----- other elements -----
<div id="supposed-parent" />
// ----- other elements -----
</div>
<div id="dialog-container">
<div id="supposed-child" />
</div>
</body>
So, how can I position #supposed-child next or beside #supposed-parent? Any help would be appreciated.
I don't think this is possible with a pure css. But with a little script we can achieve this. Take the offset-left and top of the supposed-parent and apply the same to the supposed-child. The child should be absolute positioned element. Check the below sample and It hope this will be useful for you.
Even though the supposed-child(yellow box) is independent of the supposed-parent, It will be always align with the top-left of the supposed-parent.
function offsetCalculate(){
var parentTop = $('#supposed-parent').offset();
var parentLeft = $('#supposed-parent').offset();
$('#supposed-child').css({
'top':parentTop.top,
'left': parentLeft.left
});
}
$(document).ready(function () {
offsetCalculate();
});
$(window).resize(function(){
offsetCalculate();
});
#supposed-child{
position: absolute;
background: yellow;
border-radius: 5px;
padding: 10px;
z-index: 999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="root">
<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui.</h1>
<div id="supposed-parent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer dolor libero, euismod et nisl eu, imperdiet elementum neque. Praesent aliquet non tellus sed blandit. Ut vitae velit eget turpis ornare convallis. Quisque nec felis eget mi vestibulum luctus eu non dui. Pellentesque eget commodo tellus. Curabitur a dolor est. Integer dapibus lectus nec mi luctus, ac ornare ex auctor. Donec vel nisi nulla. Mauris maximus egestas nunc ut egestas. Suspendisse id leo nec elit consectetur interdum. Ut purus nibh, tristique quis est vel, ultrices blandit nibh. Aenean nibh justo, mattis sed vulputate quis, efficitur eu mauris. Sed vel vulputate metus, et dictum arcu. In ornare nisl vitae purus elementum, quis egestas dolor volutpat. In velit nisi, posuere in urna non, feugiat luctus enim.
</div>
</div>
<div id="dialog-container">
<div id="supposed-child" >This is a popup</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>

Scroll fixed content with jQuery

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;
}

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/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