Textarea Resize


10 Jan 15 - 09:54

I finally have a decent textarea resize module. I had been playing around with quite a few for this blog. Originally I was using the classic:

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on' event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight 'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}

Which was great but it kept jumping to the top of the page every time a line was added. I talk about it here a little. This morning was the last straw though, instead of breakfast, I decided to try it again and started with adding some extra code to the function.

After some Google searches I found this

function resize () {
   var scrollLeft = window.pageXOffset ||
   (document.documentElement || document.body.parentNode || document.body).scrollLeft;

   var scrollTop  = window.pageYOffset ||
   (document.documentElement || document.body.parentNode || document.body).scrollTop;

   text.style.height = "auto";
   text.style.height = text.scrollHeight   'px';

   window.scrollTo(scrollLeft, scrollTop);
}

This solved my problem… Somewhat. My textarea resize would no longer jump to the top of the page. Now it would remain in the same location (ie, it would not scroll up or down). However, the last line of my textarea would now be cut of constantly…

This was really annoying.

To hell with it. jQuery it is. Finally I stumbled across Jack Moore’s method of auto-resizing which makes use of jQuery. This not only prevented my jump back to the top of the page but it also handled the resizing like one would expect it to.

Thanks Jack!



Archives