Last active
August 29, 2015 14:19
-
-
Save mrofi/e6a8656be9705652ff1f to your computer and use it in GitHub Desktop.
Autogrow Textarea with AngularJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // MIT Licence (MIT) | |
| // Copyright (c) 2015 - Mokhamad Rofiudin | |
| // inspired by Facebook Textarea | |
| // Based on code here https://gist.github.com/thomseddon/4703968 | |
| // The Magic Sauce : http://stackoverflow.com/a/3238543/4711810 | |
| // How to use : <textarea auto-grow></textarea> | |
| // For jQuery visit here : https://gist.github.com/mrofi/a5c6bc25539eacf1750b | |
| app.directive('autoGrow', function() { | |
| return function(scope, element, attr){ | |
| var textarea = element[0]; | |
| textarea.lineHeight = parseInt(element.css("line-height"), 3); | |
| var sizeUp = function(textarea) { | |
| while(textarea.clientHeight < textarea.scrollHeight){ | |
| var height = textarea.clientHeight + textarea.lineHeight; | |
| $(textarea).css("height", height); | |
| } | |
| }; | |
| var sizeDown = function(textarea) { | |
| do { | |
| var height = textarea.clientHeight - textarea.lineHeight; | |
| $(textarea).css("height", height); | |
| } while(textarea.clientHeight >= textarea.scrollHeight) | |
| sizeUp(textarea); | |
| }; | |
| element.data('oldValue', textarea.value); | |
| sizeDown(textarea); | |
| element.bind('focus focusin keyup', function() { | |
| textarea.interval = setInterval(function() { | |
| if (element.data('oldValue').length < textarea.value.length) { | |
| sizeUp(textarea); | |
| } else if (element.data('oldValue').length > textarea.value.length) { | |
| sizeDown(textarea); | |
| } | |
| element.data('oldValue', textarea.value); | |
| }, 20); | |
| }).bind('focusout blur', function() { | |
| clearInterval(textarea.interval); | |
| }); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment