JavaScript - Readmore.js - Method is not a function - javascript

I am attempting to implement readmore.js into my code but I am continuously running into readmore.js is not a function error. I've read over the documentation multiple times and I am unable to figure out what I am doing wrong. When implemented correctly should include a "READ MORE" button to expand the text in its entirety.
I've included the HTML script tag that is presented in the github
I've made sure I included a jquery cdn before the readmore.js
I've included a class name of article
I've attempted to wrap the .readmore in a function such as :
$(function () { $('.article').readmore({speed: 75, lessLink: 'Read less'});});
Here is a snippet of code that I am working with:
const data = [{ paragraph: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis id aliquam nibh. Aenean a porttitor ipsum. Vestibulum ut sagittis dui, nec pharetra eros. Vivamus tempus fringilla dictum. Maecenas facilisis auctor magna, a accumsan nunc molestie dictum. In tempus rhoncus condimentum. Aenean interdum leo et velit pellentesque dapibus. Vivamus nunc orci, commodo sit amet dui a, lobortis finibus arcu. Maecenas metus mauris, tincidunt sit amet ex id, gravida commodo nunc. Donec consequat tristique lacinia. Pellentesque commodo eu tortor sit amet rutrum. Vivamus mollis eros ipsum, in vestibulum lorem tempor sit amet. Morbi egestas orci sem, posuere rutrum augue malesuada eget. Mauris ultricies egestas luctus. Praesent at dignissim nunc. Aliquam erat volutpat."},{
paragraph: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nullam porttitor tincidunt fringilla. In ullamcorper vitae sapien eget ornare. Nulla quis lacus condimentum lacus tincidunt consectetur ut in ante. Suspendisse a eleifend est. Pellentesque eu ornare magna. Vestibulum ac mi sit amet arcu tristique volutpat in id nisl. Aenean interdum et odio gravida hendrerit. Pellentesque at diam lacus. Mauris elementum ultricies imperdiet. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus ligula, molestie at laoreet id, convallis et felis. Nullam molestie, augue vel interdum semper, dui massa feugiat risus, non sodales est massa non arcu. Vivamus ut sodales metus."
}
]
let htmlOutput = ""
for (let i = 0; i < data.length; i++) {
htmlOutput += "<div>" + data[i].paragraph + "</div>"
}
$("#report").html(htmlOutput)
$('.article').readmore({
speed: 75,
lessLink: 'Read less'
});
<div id="report" class="article">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/node_modules/readmore-js/readmore.min.js"></script>
My expected outcome is to be able to include the .readmore function and have a "read more" that will expand the text once clicked.

You will have to download the readmore.min.js file from the repo. The file is located here.
https://github.com/jedfoster/Readmore.js/blob/master/readmore.min.js
Then you can include it in your project by putting it in the same directory as your index.html file and add a script tag like this
<script src="readmore.min.js"></script>

hi this might have been solved but ill add my 2c.
from your code it seem that you are adding the text inside a nested div instead of the parent div with the article class.
try adding "id='report' class= 'article' " inside the for loop div and check if the plugin works

Related

Generate highlighted and summarized search preview using javascript

I'm trying to implement a function that yields highlighted and summarized preview of the given text. Please see the following code snippet.
<div>
Search:
<input value='vestibulum' disabled/>
</div>
<div style='margin-top: 20px'>Output I want:</div>
<div style='border: 1px solid #000; padding: 10px'>
...diam lectus <mark>vestibulum</mark> risus, eu <mark>vestibulum</mark> turpis quam in lorem. Vivamus posuere nibh leo, sit amet pharetra velit convallis sed. Sed porta convallis justo ac auctor. <mark>Vestibulum</mark> ante ipsum primis in faucibus orci luctus...
</div>
<div style='margin-top: 20px'>Original Text:</div>
<div style='border: 1px solid #000; padding: 10px'>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean at lacus tempus, pharetra dui vel, egestas massa. Integer metus enim, varius sed quam sed, convallis volutpat lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam efficitur, tortor quis sagittis sollicitudin, diam lectus vestibulum risus, eu vestibulum turpis quam in lorem. Vivamus posuere nibh leo, sit amet pharetra velit convallis sed. Sed porta convallis justo ac auctor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Nulla et luctus leo, eu dignissim nunc. Phasellus vel fringilla sapien. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aenean et dui ut ipsum pretium ullamcorper. Aenean hendrerit dolor et lorem auctor ullamcorper.
</p>
<p>
Donec aliquet, purus ut tempor efficitur, velit eros luctus turpis, in pretium elit augue vel eros. Morbi eget dui ullamcorper, semper magna sit amet, cursus nulla. Aenean augue dolor, varius eu orci a, efficitur auctor diam. Quisque tempor lacus dolor. Aliquam erat volutpat. Donec imperdiet pellentesque nunc, sed accumsan sem lacinia sed. In hac habitasse platea dictumst. Nam placerat odio et leo ultricies ultrices. Cras nulla lacus, maximus in risus ut, auctor auctor vestibulum.
</p>
</div>
The function I want to implement should look like this:
const getSummarizedPreview = (query, text, windowSize) => {
// query: The word that should be highlighted. It's just one word, not a phrase.
// text: Original Text.
// windowSize: The maximum length of text returned.
}
Note that the last word of the text is also vestibulum, but getSummarizedPreview smartly chose more relevant part of the text based on the frequency of the query.
I think this might be pretty complicated to implement, so any advice, pseudocode, or introduction to library that does the simliar thing would be appreciated.
Thank you.
You can use full text search of Elasticsearch. See quick intro here.
OR you can implement this feature by yourself:
Look in your original text i see it have multi paragraph ( tag). You can split it into an array, then loop all of this array elements.
In the loop, using regex like below to find count frequency of appearance of query word:
var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);
Get element have max count.
Replace query word with highlighted query word, like: vestibulum with <mark>vestibulum</mark>
Return formatted string for display highlighted matched query word.
This is an interesting question and I am also looking for a better solution.

change javascript html, use jquery css [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
i have a javascript worked html code. but i dont need a html, i need a jquery css
which have the same functionality.
i try to change js html by jquery css but it does not worked
js html
$('html, div:contains('+yourstring+')', document.body).each(function(){
console.log(this);
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi'), '<span class=someclass>'+yourstring+'</span>'
));
});
to css query
$('html, div:contains('+yourstring+')', document.body).each(function(){
console.log(this);
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi').css('background-color' 'blue')
));
});
In your example, this code, will not work:
$('html, div:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'gi').css('background-color' 'blue')
));
});
Since a new RegExp is not a jQuery Object, you cannot call .css() up it. You must still have an HTML Element or a jQuery Object to work with.
Another thing to be aware of is that :contains() is case sensitive. So if you're testing with "test" it will not find "Test" in your <div> element. So you may have some search issues right away with this selector.
Consider this example:
$(function() {
function replacer(sObj, n) {
var c = sObj.text().trim().split(" ");
var re = new RegExp(n, "i");
var hits = [];
$.each(c, function(k, v) {
if (v.match(re) != null) {
hits.push(k);
var newObj = $("<span>", {
class: "highlight"
}).html(v);
c[k] = newObj.prop("outerHTML");
}
});
sObj.html(c.join(" "));
return hits;
}
$("div").each(function(ind, el) {
replacer($(el), "lorem");
});
});
.para {
margin: 10px;
}
.highlight {
background-color: #ccf;
padding: 0.02em;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="para">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel dictum nunc, nec pellentesque elit. Integer eget tempor tellus, sit amet volutpat purus. Proin magna est, sollicitudin in suscipit quis, tincidunt at lacus. Morbi sollicitudin sit amet justo
sit amet pellentesque. Nunc placerat ligula sapien, non laoreet tellus dictum ac. Fusce est leo, bibendum ac justo sit amet, rhoncus placerat enim. Mauris sit amet lectus felis. Aenean eget feugiat leo, rhoncus hendrerit felis. Donec placerat mi quis
justo varius tempor. Nunc ultricies mi in dolor placerat, non consequat est lobortis. Quisque ac libero in sem cursus pharetra. Fusce pretium rutrum viverra.</div>
<div class="para">Nullam tincidunt ut nisl eu venenatis. Duis non finibus orci, nec imperdiet augue. Sed consectetur orci ut magna sollicitudin sagittis. In mattis tempus molestie. Suspendisse vitae hendrerit nulla. Sed scelerisque metus eros, eu molestie felis auctor
convallis. In tempor mauris non mi bibendum mollis. Nulla eu sapien non mi aliquam interdum. Donec lorem elit, tincidunt nec lorem at, finibus commodo mauris.</div>
<div class="para">Donec non lectus auctor, imperdiet ante quis, varius erat. Aenean vitae mi magna. Nunc dui tortor, dictum volutpat porta quis, hendrerit nec nunc. Morbi blandit, lectus eget ultrices vestibulum, odio arcu rutrum sem, quis placerat lectus dui sit amet
augue. Phasellus congue gravida tortor. Sed nec mauris tempus, convallis justo ac, sollicitudin mauris. Pellentesque pretium facilisis augue in dignissim. Pellentesque sollicitudin erat vitae consectetur lacinia. Nunc faucibus lobortis sem vel faucibus.
Suspendisse a ligula aliquet, tempus neque at, egestas mauris. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam eleifend felis lorem. Vivamus sollicitudin, purus nec finibus luctus, dui urna tincidunt est, posuere imperdiet erat magna
quis turpis. Donec vestibulum nisl eu porttitor laoreet.</div>
<div class="para">Duis vel nibh a libero elementum porttitor sit amet feugiat nisl. Quisque nec maximus turpis. Maecenas in libero sit amet urna consectetur posuere. Maecenas vulputate vitae eros a malesuada. Nullam malesuada nulla et varius aliquam. Nulla hendrerit mi
ac nisi scelerisque, id molestie nibh ultricies. Vivamus venenatis, diam ac vehicula gravida, magna diam consectetur nibh, ac mollis libero enim a orci. Nam tincidunt est id vulputate ullamcorper. In nec lectus blandit, ullamcorper tortor vel, ornare
neque. In accumsan tempus orci in finibus. Mauris ac fermentum dui, ac volutpat erat.</div>
<div class="para">Praesent sed purus risus. Quisque porttitor suscipit feugiat. Quisque est massa, porttitor ut feugiat vel, consectetur nec mauris. Fusce iaculis lacus vel felis rhoncus accumsan. Vestibulum interdum lacus magna, id gravida tellus sollicitudin in. Cras
mauris turpis, elementum a imperdiet ut, faucibus sit amet elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec venenatis eget libero ut aliquet. Praesent a mollis est, ut consequat arcu. Sed nec
molestie diam. Nunc vestibulum consectetur odio non accumsan. Suspendisse eget tempus lacus. Cras quis dignissim odio, eget tincidunt nulla.</div>
This might be overboard from what you want to do. It's a good way to highlight words with a loop.
Hope that helps.

Javascript and Html; get page from URL

I am creating a website for a client and they have given me some very strict limitations. The html must be coded in one document (index.html), with the javascript and css each in their own separate document. They also want me to use Angular or Node only if necessary (it has not been necessary so far).
Since they are requiring multiple “pages” on the website, I am using Javascript to hide or unhide different divs corresponding to each page. I also have the separate divs internally referenced. Therefore, when the maps “page” is open the URL displays as https:\\site.com\#maps . When the page gets reloaded, it ignores the #maps and simply returns to the main “page”.
I have tried using window.location to get the url when the page is loaded, then pass that to my function; however, that has not worked. I also briefly tried messing with cookies to save the page location, but wasnt able to get very far with it.
How can I get the function to load the page I want based on the url?
function openPage(evt, PageName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the link that opened the tab
document.getElementById(PageName).style.display = "block";
evt.currentTarget.className += " active";
//set the page cookie
var expiry = new Date();
expiry.setTime(expiry.getTime()+600000);
expires = "; expires=" + expiry.toUTCString();
document.cookie = "Page=" + PageName + expires + " ; path=/";
}
Well, each div element has to have the id attribute, this attribute identifies the page/div and will be set as value for the window.location.hash.
Than handle all click events which trigger the page change, for instance all a elements with href attribute set to these ids.
Then create function which will show/hide the desired page, and call this method when the whole html page is loaded.
Here is an example using jQuery (if you want there is no need to use jQuery, you can do it with vanilla javascript as well):
$(function() {
// Method wich show/hide pages
function showpage(target) {
// Target is the id of the page div
var $target = $(target);
// If there is not any page with that id do nothing
if(!$target.length) {
return;
}
// Hide all pages
$(".page").css("display", "none");
// Show the target page
$target.css("display", "block");
// Update the window has
window.location.hash = target;
}
// Handle clicks which show pages
$(document).on("click", "a[href^='#']", function (e) {
e.preventDefault();
showpage($(this).attr("href"));
});
showpage(window.location.hash);
});
.page {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
page1
</li>
<li>
page2
</li>
<li>
page3
</li>
<li>
page4
</li>
</ul>
<div id="page1" class="page">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus interdum velit pretium porttitor aliquam. Proin a lectus nec ligula laoreet tempor. In ornare volutpat velit, non semper mauris accumsan nec. Aliquam nibh nisi, pellentesque eu mauris eu, fringilla faucibus leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pretium, tortor eget scelerisque luctus, enim quam elementum diam, ac varius elit tortor eu tortor. Morbi molestie massa nec aliquam fringilla.
</div>
<div id="page2" class="page">
Maecenas sagittis convallis turpis, sed fermentum magna porttitor eget. Aenean et lectus eu velit interdum aliquet. Duis faucibus sollicitudin iaculis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent suscipit pulvinar felis, at fermentum dolor ultrices non. Maecenas malesuada urna lorem, mollis lobortis nisi semper et. Quisque ac tellus interdum, hendrerit nisl eu, feugiat ante. Nullam tincidunt ex non metus venenatis suscipit. Duis rutrum convallis erat, quis ultrices nunc efficitur sed. Donec lacinia tellus eu neque tempus, eu bibendum odio sollicitudin. Nullam convallis ligula vitae sapien tristique, eget ullamcorper risus pulvinar. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec tincidunt, sapien vel eleifend laoreet, tortor dolor ultrices est, consequat suscipit neque metus a velit. Maecenas cursus nec arcu et varius. Nulla ex lorem, mollis eu risus quis, molestie dapibus nisl. Maecenas vel imperdiet mauris, ut pretium odio.
</div>
<div id="page3" class="page">
Donec mi mi, placerat tincidunt justo sit amet, facilisis congue sapien. Nunc lacinia lobortis turpis ac rhoncus. Donec tempus elit vitae pharetra congue. Nam at dolor at metus hendrerit pharetra nec et velit. Morbi iaculis ipsum non finibus hendrerit. Nunc eget ex non augue feugiat venenatis a sit amet nisl. Vestibulum elementum ipsum non enim pulvinar malesuada. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis et purus vitae libero lobortis gravida et eu lectus. Aenean dignissim molestie ante a iaculis.
</div>
<div id="page4" class="page">
Pellentesque iaculis diam a condimentum aliquam. Integer vestibulum interdum ligula, quis tempus felis aliquam at. Ut vel tincidunt purus, quis convallis ipsum. Pellentesque massa velit, varius gravida purus nec, consectetur suscipit nibh. Vivamus vel dui sit amet magna condimentum sodales ac a urna. Sed viverra, dolor sit amet facilisis commodo, tortor massa efficitur neque, sit amet sollicitudin lectus augue sed est. Nulla dapibus facilisis magna, vestibulum maximus dui gravida convallis. Sed sit amet tellus non velit tincidunt mollis vitae vitae purus. Donec sed molestie lacus. Morbi condimentum sapien nec odio scelerisque bibendum.
</div>
Use the onload property on your body tag:
<body onload="pageLoaded(window.location.hash)">
https://www.w3schools.com/jsref/event_onload.asp

Toggle an Image on Click

I'm trying to toggle an image on Click. It's partially working but also partially not :'(
Demo: http://jsfiddle.net/Tqwdh/4/.
When I click the large image, the smaller image changes (from 50x50 to 151x151) - hurrah!
But when I click the 'Read more' text, the small image remains the same image. The small, nested image needs to change when I click the 'Read more' text.
Can anyone show me how I can resolve this?
I've attached my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});
$(function(){
$("article").click(function(){
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50'
)
)
});
});
and my HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Praesent sem lectus, ullamcorper eget ullamcorper a, congue vel nisl. Nullam volutpat leo vel dui venenatis dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus ac scelerisque lorem. Ut blandit magna eu turpis posuere gravida. Fusce egestas risus in libero ullamcorper sagittis. Vestibulum molestie metus vitae quam dignissim consequat. Vivamus id tellus id lorem consectetur iaculis sit amet interdum ante. Quisque lacinia tellus id mi tincidunt fermentum dignissim velit laoreet. Quisque scelerisque nunc iaculis nisi varius ultrices.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/50x50" class="small" style="position:absolute;margin-left: 240px;margin-top: 127px;" />
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article>
Many thanks for any pointers.
So, if I have understood you correctly, all you've got to do is,
Change this
$("article").click(function() {
//your code here
});
to,
$("article, .adjust").click(function() {
//your code here
});
Check the fiddle here
EDIT:
Changed a couple of things to match what you needed,
1) Change this,
$(this).parents('article').find('.adjust').click();
to,
$(this).parents('article').find('.adjust').trigger('click');
as the latter is a proper way to trigger an event.
2) Change in the image swap function,
$("article, .adjust").click(function() {
/*Save references in variables*/
var imgToSwap = $(this).parents("article").find("img.small");
var img_small = 'http://placehold.it/50x50';
var img_large = 'http://placehold.it/151x151';
imgToSwap.attr('src', (imgToSwap.attr('src') == img_small ? img_large : img_small));
});
Using $(this) will help you get the image in the right context.
Check the fiddle test here
It looks like you have a few problems here. I don't see that you've applied the adjust class to any element in your HTML. I also see that CSS is applied directly in JavaScript. (Why not use a .css file?)
This part of the code looks very nice:
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
This is good use of the ternary operator.
My I suggest that you use this code as the click handler on a.adjust, assuming that the link that expands the image is supposed to be decorated with the adjust class?
var changeImage = function() {
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
});
$('a.adjust').click(changeImage);
$('article').click(changeImage);
I hope this helps. If the question were written more precisely, it might be helpful.

jQuery.. div reveal/slide?

I have a div, which has content in it.
The content could be really long, or the content could be really small.
I don't want the content to stretch the page on page load if it is long, I want them to click a "more" link and it will slide down and reveal the rest of the content.
For example:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vulputate mi egestas ligula feugiat volutpat. Morbi eros felis, aliquam in varius id, sodales quis nunc. Nulla sagittis consectetur arcu, sed auctor odio placerat quis. Praesent vitae lacus neque. Curabitur ultricies tristique sollicitudin. Suspendisse malesuada nunc at augue interdum at facilisis ipsum gravida.
Below it is a bar or link that says "show the rest"
Up on click, this div lengthens and shows the rest of the content:
Nunc congue sapien sed sem tincidunt ut adipiscing neque lacinia. Praesent facilisis quam sed tellus sodales id tristique massa ullamcorper. Donec sem turpis, cursus in elementum id, tincidunt a libero. Etiam feugiat, sem quis dictum imperdiet, nisl ante pharetra erat, ut ornare nulla justo ac sapien.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Suspendisse vulputate mi egestas
ligula feugiat volutpat. Morbi eros
felis, aliquam in varius id, sodales
quis nunc. Nulla sagittis consectetur
arcu, sed auctor odio placerat quis.
Praesent vitae lacus neque. Curabitur
ultricies tristique sollicitudin.
Suspendisse malesuada nunc at augue
interdum at facilisis ipsum gravida.
Nunc congue sapien sed sem tincidunt
ut adipiscing neque lacinia. Praesent
facilisis quam sed tellus sodales id
tristique massa ullamcorper. Donec sem
turpis, cursus in elementum id,
tincidunt a libero. Etiam feugiat, sem
quis dictum imperdiet, nisl ante
pharetra erat, ut ornare nulla justo
ac sapien.
I know itll be hard to control what will be cut off, blah blah but it isn't for that type of thing. The div does not contain text, it contains a list of features, for example X listing may have 4 features, Z listing may have 14 features, instead of the page stretching if the listing has 14 features listed vertically, we want it to only show a few and then they must click "show me more" for it to slide down and reveal the rest.
How would I go about doing this? Even a jsfiddle to demonstrate it?
Thank you :)
Try giving a fixed height to the div. You can use CSS for this. Then compare height of the list with the outer div. If it is greater show the bar with link show more. On click of this bar you can manage the height of outer div. Like this -
CSS
.parentDiv{
height:some fixed height px;
overflow: auto;
}
Jquery
var parentHeight = $('.parentDiv').height();
var listHeight = $('#List').outerHeight(true);
if(parentHeight < listHeight) {
$('#linkBar').show();
}
$('#linkBar').click(function(){
//$('.parentDiv').height(listHeight);
//OR you can use following code to animate the div
$('.parentDiv').animate({'height': listHeight}, 'slow')
});
Here's a working demo of my implementation (coincidentally similar to the answer given above; I was making this before any answers were given): http://jsfiddle.net/7fhrN/15/
It works for users without JavaScript and gives graceful degradation to your page. Try switching the JS library to something random on JsFiddle and click Run.
HTML:
<div class="stretchy">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vulputate mi egestas ligula feugiat volutpat. Morbi eros felis, aliquam in varius id, sodales quis nunc. Nulla sagittis consectetur arcu, sed auctor odio placerat quis. Praesent vitae lacus neque. Curabitur ultricies tristique sollicitudin. Suspendisse malesuada nunc at augue interdum at facilisis ipsum gravida.</div>
<div class="stretchy">Nunc congue sapien sed sem tincidunt ut adipiscing neque lacinia. Praesent facilisis quam sed tellus sodales id tristique massa ullamcorper. Donec sem turpis, cursus in elementum id, tincidunt a libero. Etiam feugiat, sem quis dictum imperdiet, nisl ante pharetra erat, ut ornare nulla justo ac sapien. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vulputate mi egestas ligula feugiat volutpat. Morbi eros felis, aliquam in varius id, sodales quis nunc. Nulla sagittis consectetur arcu, sed auctor odio placerat quis. Praesent vitae lacus neque. Curabitur ultricies tristique sollicitudin. Suspendisse malesuada nunc at augue interdum at facilisis ipsum gravida. Nunc congue sapien sed sem tincidunt ut adipiscing neque lacinia. Praesent facilisis quam sed tellus sodales id tristique massa ullamcorper. Donec sem turpis, cursus in elementum id, tincidunt a libero. Etiam feugiat, sem quis dictum imperdiet, nisl ante pharetra erat, ut ornare nulla justo ac sapien.</div>
CSS:
.stretchy
{
margin: 20px;
padding: 5px;
background-color: rgb(240, 240, 240);
overflow: hidden;
position: relative;
padding-bottom: 20px;
}
.inner
{
max-height: 120px;
overflow: hidden;
}
.reveal
{
position: absolute;
bottom: 0px;
}
JavaScript:
$(document).ready(function()
{
$('.stretchy').each(function()
{
if ($(this).height() > 130)
{
$(this).replaceWith('<div class="stretchy"><div class="inner">' + $(this).html() + '</div>Show me more lipsum</div>');
}
});
$('.reveal').toggle(function()
{
$(this).parent().find('.inner').animate({maxHeight: '1000px'});
}, function() {
$(this).parent().find('.inner').animate({maxHeight: '120px'});
});
});
Basically, I iterate over all the <div>s with the class stretchy. If they are too big, I replace them with a <div> with a container and a link at the bottom which changes the max-height of the inner <div> to some ridiculous value.
Just try it. Seeing > having me explain it to you.

Categories