DaveDev
DaveDev

Reputation: 42185

How to apply a $(document).ready function to asynchronously loaded elements?

I have the following function which applies watermark text to any text box on the page with the id "Search":

jQuery(document).ready(function ($) {

    $("#Search").watermark({
        watermarkClass: 'watermarkOn',
        defaultText: $("#Search").attr("watermarkText")
    });
});

The problem I'm having is that that this doesn't get applied when I asynchronously load a panel that contains the text box, because it occurs in the jQuery(document).ready function, which has already fired.

Is there anything I can do to make sure that any asynchronously loaded text boxes have this function applied to them? Thanks.

Upvotes: 3

Views: 438

Answers (2)

Moin Zaman
Moin Zaman

Reputation: 25445

look up the .live() method to bind events, to elements created previously, or in the future, as in your case, asynchronously.

Ref: http://api.jquery.com/live/

It may be possible to alter the watermark plugin / method you have to use .live()

.live() will only work for events and it won't allow you to attach a plugin to elements that will be created in the future.

For that you can look at liveQuery a plugin that will allow you to attach plugins to elements that may be created in the future.

eg.

//initiate the watermark plugin on all elements with class 'search' existing now or created in the future.
    $('.Search').livequery(function() {
        $(this).watermark({
            watermarkClass: 'watermarkOn',
            defaultText: $("#Search").attr("watermarkText")
        });
    });

Upvotes: 0

user113716
user113716

Reputation: 322492

If you're using $(selector).load(), then call the .watermark() in the callback.

$('someSelector').load('/some/path', function( response ) {
    $('someNewElement').find('input').watermark({
        watermarkClass: 'watermarkOn',
        defaultText: $("#Search").attr("watermarkText")
    });
});

If the options are all the same, you could store them in a variable to be reused.

var options = {
           watermarkClass: 'watermarkOn',
           defaultText: $("#Search").attr("watermarkText")
          };

$("#Search").watermark( options );

$('someSelector').load('/some/path', function( response ) {
    $('someNewElement').find('input').watermark( options );
});

Upvotes: 3

Related Questions