Rich Rich - 2 months ago 11
Javascript Question

Reusable jQuery truncate function

So I have created the following code to deal with one instance of a string that requires truncating with expandable and collapsable click events.

$(document).ready(function () {
var Element = $("[class*='truncate']");
var FullText = $(".truncate").text();
var Show = "<span class='show'> [...]</span>";
var Hide = "<span class='hide'> [ ]</span>";
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);
});
});


Which truncates the following HTML

<div class="truncate">MBK-40B-FRLBBLCSLWLHBLHSLSALSAS32PDL</div>


The above code works perfectly for one instance of the class
.truncate
but when adding more things get a bit messy. How can I make this code work when there are many elements with this class, some of which will need to be truncated while others won't?

Answer

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?