jquery implements textarea to be highly adaptive

  • 2020-05-12 02:15:11
  • OfStack

I Shared with you before that using Javascript to control the height of the text box textarea as the content grows and shrinks adaptively. Today I spent some time to change the implementation method


jQuery.fn.extend({
            autoHeight: function(){
                return this.each(function(){
                    var $this = jQuery(this);
                    if( !$this.attr('_initAdjustHeight') ){
                        $this.attr('_initAdjustHeight', $this.outerHeight());
                    }
                    _adjustH(this).on('input', function(){
                        _adjustH(this);
                    });
                });
                /**
                 * Reset the height
                 * @param {Object} elem
                 */
                function _adjustH(elem){
                    var $obj = jQuery(elem);
                    return $obj.css({height: $obj.attr('_initAdjustHeight'), 'overflow-y': 'hidden'})
                            .height( elem.scrollHeight );
                }
            }
        });
        // use
        $(function(){
            $('textarea').autoHeight();
        });

That's all for this article, and I hope it will be helpful for you to learn jQuery.


Related articles: