0

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?

Kevin B
  • 94,570
  • 16
  • 163
  • 180
Rich
  • 33
  • 7
  • Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. – Rooster Dec 11 '13 at 21:56
  • 1
    @Rooster I didn't ask anyone to recommend a library, tool etc you may wish to reread my post? – Rich Dec 11 '13 at 21:59
  • @KevinB Wowa I clearly asked for pointers, not an entire solution. – Rich Dec 11 '13 at 22:00
  • Calm down everyone, just use this as an opportunity to explain about jQuery's `.each()` – RustyToms Dec 11 '13 at 22:01
  • @KevinB Way to start a flame war, literally won't even respond to that comment. – Rich Dec 11 '13 at 22:03
  • Rich, I recommend rewording your question to be much much more general, I'll try to edit it to make it StackOverflow appropriate, approve my edit when it is done if you like it. – RustyToms Dec 11 '13 at 22:05

2 Answers2

1

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?

RustyToms
  • 7,600
  • 1
  • 27
  • 36
  • Nothing else is being done with this code later, it's just merely for truncating strings and expanding/collapsing at the users will. Could you explain possible memory problems please? – Rich Dec 11 '13 at 22:21
  • I use Backbone.js, and it is a problem there because you are never refreshing the page. If you make event listeners for html elements, then replace those elements with other elements, the first elements won't get removed from memory because they are linked with the event listeners. In your case, if you are setting this up once, then when the user navigates the page is refreshed, I guess it isn't a big deal. But FYI, to remove `.on()` you use `.off()`, [the docs are here](http://api.jquery.com/off/) – RustyToms Dec 11 '13 at 22:29
  • Thanks very much for your help and code. (Your example misses the end }); btw) Also when using this the collapsing functionality breaks. I had this when I experimented with the this keyword before. – Rich Dec 11 '13 at 22:44
  • Fantastic - Does exactly what I want thank you! I knew I was quite close myself aha. I'll accept this answer. – Rich Dec 11 '13 at 22:58
0

https://jsfiddle.net/5dtmm9kn/

The JS

              $('[truncate]').each(function( index ) {
                var howmuch = $(this).attr('truncate');
                var title = $( this ).text();
                var shortText = jQuery.trim(title).substring(0, howmuch)
                  .split(" ").slice(0, -1).join(" ") + " <span>...</span>";
                $( this ).html(shortText);
              });

The html

<h3 truncate="40">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</h3>

The css

  [truncate] span{ 
    font-size: 0.6em;
    opacity: 0.6;
  }
Omar
  • 2,726
  • 2
  • 32
  • 65