PonyTricks
PonyTricks

Reputation: 1798

Use same functions for new DOM elements

On my site I use jQuery autosize library.

It is used on textareas, and are defined in my javascript.js file, with just:

$(".autosize").autosize();

The problem is that when I want to load new textareas into my site using ajax, I need to write this again in the ajax return. Fx:

<textarea name='something' class='autosize'></textarea>
<script type='text/javascript'>
    $(".autosize").autosize();
</script>

Is it not possible for the new textareas inserted into the DOM, to automatically "act" according to the javascript.js file from my header?

FYI, this questions is simplified a lot and the real case is on a much larger scale.

Upvotes: 1

Views: 44

Answers (1)

Mir Gulam Sarwar
Mir Gulam Sarwar

Reputation: 2648

As you are using ajax to add the item then in the global js file you may do something like below.

$(document).ajaxSuccess(function() {
   $(".autosize").autosize();
});

Using deprecated DOMNodeInserted listener

 $('body').on('DOMNodeInserted', '.autosize', function(e) {
       $(".autosize").autosize();
    });

Upvotes: 1

Related Questions