We can learn about the .each()
jQuery method, here are some docs: http://api.jquery.com/each/
.each()
will go through each element that was found with the selector and give you access to it through the this
keyword, allowing you to run your code for one element at a time.
$(document).ready(function () {
var Show = "<span class='show'> [...]</span>";
var Hide = "<span class='hide'> [ ]</span>";
$(".truncate").each(function(){
var Element = this;
var FullText = $(Element).text();
var shortString = FullText.substring(0, 5);
if (FullText.length > 5) {
$(Element).html(shortString + Show);
}
$(Element).on("click", ".show", function () {
$(Element).html(FullText + Hide);
});
$(Element).on("click", ".hide", function () {
$(Element).html(shortString + Show);
});
});
});
There are better ways to do this, but .each()
is a quick fix. What I would be concerned about is turning all those listeners off, I'm not sure what you are doing with your code later, but you don't want memory problems. Any suggestions?