Youss
Youss

Reputation: 4212

Shorten plain div text

I am using a service called 'embedly' which is showing my feeds. I'm trying to shorten the text of this feed, so I tried:

$('.description').html(
     function(){
         return $.trim($(this).html())
                .substring(0, 100)
                .split(" ").slice(0, -1)
                .join(" ") + "...";}
);

I placed this in document ready and also in 'window.load' but nothing seems to work. Here is an example: http://jsfiddle.net

Upvotes: 1

Views: 186

Answers (3)

Cranio
Cranio

Reputation: 9837

So, my other answer is not valid because the OP didn't mention that all the elements were created on the fly, so they cannot be matched in the classical way.

If the modifications are attached to a suitable event (click, for example), then it would be easy to use delegates with .on(), as they are valid also for new elements inserted in the DOM. But alas this is not the case, we must operate on the element's creation.

One solution would be @ChrisClower's one (a timer polling the page regularly for new elements).

Another solution would be to use the LiveQuery plugin: http://docs.jquery.com/Plugins/livequery

Then all would be simple:

$(".description").livequery(function() {  $(e).html(reduce($(e).html())); });

 function reduce(s)
{
     return s.substring(0, 100)
            .split(" ").slice(0, -1)
            .join(" ") + "..."; 
}

Upvotes: 0

Cranio
Cranio

Reputation: 9837

Jquery's HTML doesn't accept a function as argument, but only plain HTML (a string). To do what you wanto to do, use .each() :)

Correction: as pointed out by the commenter below, my code is correct but .html() does indeed accept a function as argument, in the form $(...).html(function(index, oldhtml));, making possible to access directly the html part. (Thanks to @Raminson for pointing it out)

Prior to @Raminson's observation my code was:

$('.description').each(
     function(i,e){
         $(e).html(reduce($(e).html()));}
);

function reduce(s)
{
         return s.substring(0, 100)
                .split(" ").slice(0, -1)
                .join(" ") + "...";
}

With the correction, the first part becomes (still using the reduce() function):

$(".description").html(function(i,s) { return reduce(s); });

Upvotes: 2

Chris Clower
Chris Clower

Reputation: 5104

This one took me a very long time to figure out, but I think the best you can do is give the elements a second to load into the DOM, and then run your function: http://jsfiddle.net/2VBSX/5/

$('div.newscontainer').embedly({
    key:':e0a98aba95ef11e09dcd4040d3dc5c07'
}).hide();

setTimeout(function() {
    $('div.newscontainer').show().find('.description').html(
        function(){
            return $.trim($(this).html())
            .substring(0, 100)
            .split(" ").slice(0, -1)
            .join(" ") + "...";
        }
    );
}, 1000);

Upvotes: 2

Related Questions