Skip to content

Instantly share code, notes, and snippets.

@AndreKelling
Last active August 29, 2018 06:52
Show Gist options
  • Save AndreKelling/6aa230a49b9e520764d52756970c9f45 to your computer and use it in GitHub Desktop.
Save AndreKelling/6aa230a49b9e520764d52756970c9f45 to your computer and use it in GitHub Desktop.
jQuery readMore reveal
/*
* use like:
* <p data-readmore="fazit" data-readmore-maxlines="3">bla bla long text...</p>
* <div data-readmore-toggle="fazit" class="fs-smaller clickable clr-blue">...more</div>
*
* while `data-readmore` activates the functionality and `fazit` works as selector id for the toggle `data-readmore-toggle`.
* activator and toggle need to be in the same parent container!
*/
'use strict';
var ReadMore = (function($) {
var plugin = {};
plugin.init = function() {
$('[data-readmore]').each(function () {
plugin.activate(this);
})
};
plugin.activate = function(el) {
var jqel = $(el);
// add max lines shown height
var lineHeight = parseFloat(jqel.css('line-height'));
var fontSize = parseFloat(jqel.css('font-size'));
var maxHeight = jqel.data('readmore-maxlines') * (lineHeight / fontSize) * 0.95;
var readMoreHeight = (jqel.data('readmore-maxlines') - 1) * (lineHeight / fontSize) * 0.95;
jqel.height(maxHeight + 'em');
// show readMore toggle if needed
var offsetHeight = el.offsetHeight;
var scrollHeight = el.scrollHeight;
var toggle = jqel.parent().find('[data-readmore-toggle="' + jqel.data('readmore') + '"]');
toggle.hide();
jqel.css('overflow','hidden');
if (offsetHeight < scrollHeight) {
toggle.show();
jqel.height(readMoreHeight + 'em');
toggle.on('click', function() {
jqel.height('auto');
$(this).hide();
});
}
};
return {
init: plugin.init
};
}(jQuery));
$(document).ready(function() {
ReadMore.init();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment