Skip to content

Instantly share code, notes, and snippets.

@CyrilKrylatov
Last active December 11, 2015 11:19
Show Gist options
  • Save CyrilKrylatov/4593141 to your computer and use it in GitHub Desktop.
Save CyrilKrylatov/4593141 to your computer and use it in GitHub Desktop.
Truncate too long text
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Truncate code</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style type="text/css">
* {
margin:0;padding:0;
}
div {
border:1px red solid !important;
width:290px;
}
</style>
</head>
<body>
<div class="too-long-text"><span>Ce texte est beaucoup</span> trop long et va passer sur 3 lignes car la div ne fait pas beaucoup + de 3 lignes ! lol ;-)</div>
<script type="text/javascript">
jQuery(".too-long-text").each(function (i, el) {
// We set into a var the text of the element (el) found by the .each();
var leTexte = $(el).text(),
// How many chr we want?
limiteTexte = 80,
// Truncing the text with substr();
troncateTexte = leTexte.substr(0,limiteTexte),
// Adding "..."
newTexte = troncateTexte += "...";
// Changing the too long text by the new trunced one.
jQuery(el).text(newTexte);
/*
For the glory (of Lucifer, jQuery's father), all in one line :
jQuery(el).text(jQuery(el).text().substr(0,80) +"...");
*/
/*
Nice & complete review from @doxeone
jQuery(el).text(function(i, txt){
return txt.substr(0,80) +"...";
});
*/
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment