user3932810
user3932810

Reputation:

Single script for text truncation in multiple divs

This is continuation of my previous question.

Answer given by Joffrey worked fine But problem in that is, It loads the same content in all the divs which has the same class name.

This should work independently for each divs. If you check the demo attached, you can see all the divs are displaying the same content as first div even though each div has different content.

Here is the code used

var text = $('.truncate, .truncate_another').text();
    var shortText = $.trim(text).substring(0, 50).split(" ").slice(0, -1).join(" ") + "...";
    $('.truncate, .truncate_another').text(shortText);

    $('.truncate, .truncate_another').hover(function(){
        $(this).text(text);
        $('.truncate, .truncate_another').css('z-index', '10');
        $(this).css('z-index', '100');
    }, function(){
        $(this).text(shortText);
    });

DEMO Here

Upvotes: 0

Views: 109

Answers (1)

vesse
vesse

Reputation: 5078

Setting properties to outcome of $('.truncate, .truncate_another') will, as you've noticed, affect every matching item. Loop over the items to handle them separately:

$('.truncate, .truncate_another').each(function() {
  var text = $(this).text();
  var shortText = $.trim(text).substring(0, 50).split(" ").slice(0, -1).join(" ") + "...";
  $(this).text(shortText);

  $(this).hover(function(){
    $(this).text(text);
    $('.truncate, .truncate_another').css('z-index', '10');
    $(this).css('z-index', '100');
  }, function(){
    $(this).text(shortText);
  });
});

Upvotes: 2

Related Questions