Reputation: 29
Textarea change needs to be detected onkeyup event when page is loading. Textarea resizing is working fine but textarea is not detected onkeyup event when page is loaded.I tried following code.
<script>
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
jQuery(this).on('keyup input', function () {
resizeTextarea(this);
});
jQuery(this).trigger('keyup');
});
</script>
Upvotes: 0
Views: 210
Reputation: 6807
try by running your code in window.onload
window.onload=function(){
jQuery.each(jQuery('textarea[data-autoresize]'), function() {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function(el) {
jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
jQuery(this).on('keyup input', function() {
resizeTextarea(this);
});
jQuery(this).trigger('keyup');
});
//trigger when modal showing
$('.modal').on('shown.bs.modal', function () {
jQuery('textarea[data-autoresize]').trigger('keyup');
})
}
fiddle here
Upvotes: 2
Reputation: 1331
You shall execute jquery once the doc has finished loading.
Wrap it like this:
<script>
$(document).ready(function(){
jQuery.each(jQuery('textarea[data-autoresize]'), function () {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function (el) {
jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
jQuery(this).on('keyup input', function () {
resizeTextarea(this);
});
jQuery(this).trigger('keyup');
});
});
</script>
Upvotes: 1