Created
September 18, 2013 18:20
-
-
Save jhafner/6613240 to your computer and use it in GitHub Desktop.
A tiny jQuery plugin for truncating multiple lines of text.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function(){ | |
$('.truncate').each(function(el){ | |
var $this = $(this); | |
var t_size = $this.data('text-length'); | |
$this.succinct({ | |
size: t_size | |
}); | |
}); | |
}); | |
// Markup Usage | |
// <p class="truncate" data-text-length="120">... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2013 Mike King (@micjamking) | |
* | |
* jQuery Succinct plugin | |
* Version 1.0.1 (July 2013) | |
* | |
* Licensed under the MIT License | |
*/ | |
/*global jQuery*/ | |
(function($){ | |
'use strict'; | |
$.fn.succinct = function(options){ | |
var defaults = { | |
size: 240, | |
omission: '...', | |
ignore: true | |
}, | |
options = $.extend(defaults, options); | |
return this.each(function(){ | |
var textDefault, | |
textTruncated, | |
elements = $(this), | |
regex = /[!-\/:-@\[-`{-~]$/; | |
var truncate = function(){ | |
elements.each(function(){ | |
textDefault = $(this).text(); | |
if (textDefault.length > options.size) { | |
textTruncated = $.trim(textDefault). | |
substring(0, options.size). | |
split(' '). | |
slice(0, -1). | |
join(' '); | |
if (options.ignore) { | |
textTruncated = textTruncated.replace( regex , '' ); | |
} | |
$(this).text(textTruncated + options.omission); | |
} | |
}); | |
}; | |
var init = function() { | |
truncate(); | |
}; | |
init(); | |
}); | |
}; | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Copyright (c) 2013 Mike King (@micjamking) | |
* | |
* jQuery Succinct plugin | |
* Version 1.0.1 (July 2013) | |
* | |
* Licensed under the MIT License | |
*/ | |
(function(a){a.fn.succinct=function(b){var c={size:240,omission:"...",ignore:true},b=a.extend(c,b);return this.each(function(){var e,d,h=a(this),g=/[!-\/:-@\[-`{-~]$/;var f=function(){h.each(function(){e=a(this).text();if(e.length>b.size){d=a.trim(e).substring(0,b.size).split(" ").slice(0,-1).join(" ");if(b.ignore){d=d.replace(g,"")}a(this).text(d+b.omission)}})};var i=function(){f()};i()})}})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment