Reputation: 8272
The problem is that when the textarea height is higher than the window the scroll sticks to the top of the textarea when it should be focus to where the caret is.
This is my code
function adaptiveheight(a) {
$(a).height(0);
var scrollval = $(a)[0].scrollHeight;
$(a).height(scrollval);
}
Here's a fiddle
Try to make the textarea lengthy and you'll see the problem.
As much as possible I don't want a third party plugin. Thank you
Upvotes: 2
Views: 6629
Reputation: 4958
You can simply maintain current page position after resizing the textarea:
function adaptiveheight(a) {
var $a = $(a), $window = $(window), scrollTop = $window.scrollTop();
$a.height(0).height($a.prop('scrollHeight'));
$window.scrollTop(scrollTop);
}
See https://github.com/jgonera/micro.js/blob/master/micro.autosize.js.
Upvotes: 1
Reputation: 57095
add this code in the end of adaptiveheight(a)
function
if (parseInt(a.style.height) > $(window).height() - 30) {
$(document).scrollTop(parseInt(a.style.height));
}
Working Demo http://jsfiddle.net/cse_tushar/ve4rL/3/
New Js code
$("#description").keyup(function (e) {
adaptiveheight(this);
});
i=0;
j=0;
function adaptiveheight(a) {
$(a).height(0);
var scrollval = $(a)[0].scrollHeight;
$(a).height(scrollval);
if (parseInt(a.style.height) > $(window).height()) {
if(j==0){
max=a.selectionEnd;
}
j++;
var i =a.selectionEnd;
console.log(i);
if(i >=max){
$(document).scrollTop(parseInt(a.style.height));
}else{
$(document).scrollTop(0);
}
}
}
Working Demo http://jsfiddle.net/cse_tushar/ve4rL/5/
Upvotes: 2