diff --git a/README.md b/README.md index d52c9e2..d1cdbd5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ autogrow.js Basic usage ([Interactive Demo](http://jsfiddle.net/edelman/HrnHb/)): - $('textarea').autogrow(); //or some selector that will grab textareas +```javascript +$('textarea').autogrow(); //or some selector that will grab textareas +``` **autogrow.js** has some options that you can set: @@ -20,9 +22,26 @@ Basic usage ([Interactive Demo](http://jsfiddle.net/edelman/HrnHb/)): Example: - var opts = { - context: $('li') - , animate: false - , cloneClass: 'faketextarea' - }; - $('.mytextareas').autogrow(opts); +```javascript +var opts = { + context: $('li') + , animate: false + , cloneClass: 'faketextarea' +}; +$('.mytextareas').autogrow(opts); +``` + +### Events + +`autogrow:grow` and `autogrow:shrink` events will fire when a grow or shrink animation completes (or immediately if there are no animations). You can get the textarea this applies to by looking at the `event.target` + +The event will be raised against the `context` you pass into the options. + +Example: + +```javascript +$('#context-element').on('autogrow:grow', function(e) { + var box = $(e.target); + console.log(box.height()); +}); +``` \ No newline at end of file diff --git a/autogrow.js b/autogrow.js index dbbed7b..4a691f5 100644 --- a/autogrow.js +++ b/autogrow.js @@ -57,7 +57,13 @@ ; if (oldHeight < newHeight) { //user is typing this.scrollTop = 0; //try to reduce the top of the content hiding for a second - opts.animate ? box.stop().animate({height: newHeight}, opts.speed) : box.innerHeight(newHeight); + if(opts.animate) { + box.stop().animate({height: newHeight}, {duration: opts.speed, complete: notifyGrown}); + } else { + box.innerHeight(newHeight); + notifyGrown(); + } + } else if (!e || e.which == 8 || e.which == 46 || (e.ctrlKey && e.which == 88)) { //user is deleting, backspacing, or cutting if (oldHeight > minHeight) { //shrink! //this cloning part is not particularly necessary. however, it helps with animation @@ -85,12 +91,31 @@ //if user selects all and deletes or holds down delete til beginning //user could get here and shrink whole box newHeight < minHeight && (newHeight = minHeight); - oldHeight > newHeight && opts.animate ? box.stop().animate({height: newHeight}, opts.speed) : box.innerHeight(newHeight); + if(oldHeight > newHeight) { + if(opts.animate) { + box.stop().animate({height: newHeight}, {duration: opts.speed, complete: notifyShrunk}); + } else { + box.innerHeight(newHeight); + notifyShrunk(); + } + } + } else { //just set to the minHeight box.innerHeight(minHeight); } } } + + // Trigger event to indicate a textarea has grown. + function notifyGrown() { + opts.context.trigger('autogrow:grow'); + } + + // Trigger event to indicate a textarea has shrunk. + function notifyShrunk() { + opts.context.trigger('autogrow:shrink'); + } + return that; } })(jQuery);