I wrote a code that changes the size of each textarea(which has autosize class) in the document. It works ok:
$(document).each('textarea.autosize', function(){
$(this).attr("style", "height:" + (this.scrollHeight) + "px; overflow-y:hidden;");
}).on("input", function(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
});
But my web page contents are dynamic. for click event I can do this:
$(document).on('click', '.myClass', function(){});
But for each I can't.
How can I use each for elements that they are not in the DOM yet?
Put the autosize functionality in a function that you can call when you add elements to the DOM:
function autosize() {
$(document).each('textarea.autosize', function() {
$(this).attr("style", "height:" + (this.scrollHeight) + "px; overflow-y:hidden;");
}).on("input", function(){
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
});
}
autosize();
If you add elements, you can do:
$('.add').click(function() {
$(document).append($('<textarea />', { class: 'autosize' }));
autosize();
});
Alternatively, if you don't want to add this everywhere you add something:
setInverval(autosize, 100);
Caution: This solution is considered bad for your performance! So consider using one of my other solutions.
If you only want to do this, when actually an element is added, you can listen this via MutationObserver:
var observer = new MutationObserver(function(mutations) {
var elements = [ ...mutation.addedNodes].filter((node) => node.tagName.toLowerCase() === 'textarea' && node.classList.contains('.autosize'));
if (elements.length) {
autosize();
}
});
observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
It might be better for your performance to not query already modified elements again (as pointed out in the comments):
$(document).each('textarea.autosize', autosize).on("input", resize);
function autosize() {function() {
$(this).attr("style", "height:" + (this.scrollHeight) + "px; overflow-y:hidden;");
}
function resize() {
this.style.height = "auto";
this.style.height = (this.scrollHeight) + "px";
}
autosize();
In this case you have to run both autosize() and resize() when a new element is added.