Using jQuery plugin for dynamically generated HTML

so I want to use this jQuery plugin that Stack provided me :)

Auto-size dynamic text to fill a fixed-size container

However, I need to use this on an HTML element, which is a dynamically created server. Example,

I create all the elements, convert them to HTML, and then return them as an array of Json strings basically (in HTML form) to the interface:

public JsonResult GetMessages()
{
    // do conversion work
    List<string> htmlMessages = new List<string>();
    foreach(Message message in this.messages)
    {
        htmlMessages.Add(message.toHTML());
    }
    return Json(htmlMessages);
}

And then at the front end, I add them to divin jQuery as follows:

// make my AJAX call
// in the success method I do this
for (var i = 0; i < data.length; i++)
{
    $('#containerDiv').append(data[i]);
}

Now this works great, but how would I then call a jQuery plugin for each of these elements that were added to format the text size within one of divsthe element?

+3
3

, HTML, - :

// snip...
var $container = $('#containerDiv');
for (var i = 0; i < data.length; i++)
{
    $container.append(data[i]);
}
$container.children('div').textfill({ maxFontPixels: 36 });

, , <span>, HTML, , . wee little test, , , jQuery, . :

$container.children('div').each(function ()
{
    $(this).textfill({ maxFontPixels: 36 });
});

" " - :

;(function($) {
    $.fn.textfill = function(options) {
        var fontSize = options.maxFontPixels;
        this.each(function () {
            var $this = $(this),
                ourText = $this.find('span:visible:first'),
                maxHeight = $this.height(),
                maxWidth = $this.width(),
                textHeight,
                textWidth;
            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
            } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        });
        return this;
    }
})(jQuery);

, , , div?

. ,

$container.children('div').each(function ()
{
    $(this).textfill({ maxFontPixels: 36 });
});

$container.children('div').textfill({ maxFontPixels: 36 });
+2

.load() , , dom . http://api.jquery.com/load-event/

// make my AJAX call
// in the success method I do this
for (var i = 0; i < data.length; i++)
{
var elem = data[i];
elem.load(function(){
// Plugin here.
});

    $('#containerDiv').append(elem);
}
0

It seems like it could be a task for livequery that allows you to run a function when an element is dynamically added to the DOM.

0
source

All Articles