Skip to content

Instantly share code, notes, and snippets.

@betul
Created February 9, 2017 14:47
Show Gist options
  • Save betul/e11a1e0476734c65dfbf1c1a4715235a to your computer and use it in GitHub Desktop.
Save betul/e11a1e0476734c65dfbf1c1a4715235a to your computer and use it in GitHub Desktop.
TextShortener
<div class="text-box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid reiciendis earum impedit unde corporis, deserunt debitis velit, tenetur incidunt perferendis necessitatibus ullam eligendi aspernatur nam cupiditate at, ipsum, dolorem rerum!
</div>
//text shortener
(function ($) {
$.fn.shorten = function (settings) {
var config = {
showChars: 150,
ellipsesText: "...",
moreText: "More",
lessText: "Less "
};
if (settings) {
$.extend(config, settings);
}
$(document).off("click", '.morelink');
$(document).on({
click: function () {
var $this = $(this);
if ($this.hasClass('less')) {
$this.removeClass('less');
$this.html(config.moreText);
} else {
$this.addClass('less');
$this.html(config.lessText);
}
$this.parent().prev().toggle();
$this.prev().toggle();
return false;
}
}, '.morelink');
return this.each(function () {
var $this = $(this);
if ($this.hasClass("shortened")) return;
$this.addClass("shortened");
var content = $this.html();
if (content.length > config.showChars) {
var c = content.substr(0, config.showChars);
var h = content.substr(config.showChars, content.length - config.showChars);
var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> <a href="#" class="morelink">' + config.moreText + '</a></span>';
$this.html(html);
$(".morecontent span").hide();
}
});
};
$(".text-box").shorten();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
.text-box{height:80px; width:200px;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment