alloy
alloy

Reputation: 766

How Do I Cut Off the End of AJAX Loaded Text?

I am trying to cut off (truncate) extra characters off of the end of an AJAX-loaded element with text in it. Here's how I'm loading the element:

$("#destinationElement").load("/sourcePageName .classWithinPage");

I would like to limit the length of the text inside of #destinationElement to 140 characters, but the text within .classWithinPage may be longer, so I need to cut it off after that point somehow. I'd also like to add an ellipses afterwards, if possible.

I tried adding a function afterwards that would do this (see the following) but it didn't seem to work, and I would prefer it ran before the text was added to #destinationElement, so that the script would do its work before the text displayed.

var maxLength = 140;
function shorten(element) {
  var text = $(element).text();
  if(text.length > maxLength){
    text = text.substring(0, maxLength);
    var lastIndex = text.lastIndexOf(" ");
    text = text.substring(0, lastIndex) + '...';
  }  
  $(element).text(text);
};
shorten('#destinationElement');

^^ That didn't work. Plus, I think I should probably be adding in my function as a part of the jQuery load function I have up above, I'm just not sure how.

How do I truncate the text that's being loaded to 140 characters before it appears on-screen?

Upvotes: 1

Views: 149

Answers (1)

adeneo
adeneo

Reputation: 318302

Use the $.get method instead if you want to modify the data

$.get('/sourcePageName', function(data) {
    var text = $('<div />', {html : data}).find('.classWithinPage').text();

    if (text.length > 140) {
        text = text.slice(0, 140) + '...';
    }

    $("#destinationElement").text(text);
});

Upvotes: 2

Related Questions