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

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

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

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

The problem I am facing is that this does not apply when I asynchronously load a panel containing a text field because it occurs in an already executed jQuery(document).readyfunction.

Is there anything I can do to make sure that for any asynchronously loaded text fields this function applies to them? Thank.

+3
source share
2 answers

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

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

, , .

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

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

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

.live() , , , , , .

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

, / watermark, .live()

.live() , , .

liveQuery , , .

.

//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")
        });
    });
0

Source: https://habr.com/ru/post/1763329/


All Articles