So I have a problem with this auto-resize function I grabbed off the internet (By Adam Beres-Deak). Everything works perfectly except one small problem; say the textarea has 100 lines (or more than the page can fit) and say you go and edit something in the middle, the screen will jump all the way up to make the text RIGHT at the bottom of your browser/screen.
(function(){
function adjustHeight(el, minHeight){
var outerHeight = parseInt(window.getComputedStyle(el).height, 10);
var diff = outerHeight - el.clientHeight;
el.style.height = 0;
el.style.height = Math.max(minHeight, el.scrollHeight + diff) + 'px';
}
var textAreas = [].slice.call(document.querySelectorAll('textarea[data-adaptheight]'));
textAreas.forEach(function(el){
el.style.boxSizing = el.style.mozBoxSizing = 'border-box';
el.style.overflow = 'hidden';
var minHeight = el.scrollHeight;
el.addEventListener('input', function(){
adjustHeight(el, minHeight);
});
window.addEventListener('resize', function(){
adjustHeight(el, minHeight);
});
adjustHeight(el, minHeight);
});
}());
<textarea data-adaptheight rows="2" cols="40" placeholder="Your input" style="padding: 7px; line-height: 1.5;width: 100%;display: block;"></textarea>
Does anybody have any idea what can be causing this? Im not the greatest at javascript, but I did try to look it over and see what could be causing it but I had no success.
Would greatly appreciate the help guys, Thank you!
Answer:
After reviewing the answer on question: https://stackoverflow.com/a/18262927/13231904
I was able to merge the code from this question with the code from that answer for a very effective function:
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 textAreas = [].slice.call(document.querySelectorAll('textarea[data-adaptheight]'));
textAreas.forEach(function(el){
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;
el.style.resize = "none";
el.style.overflow = 'hidden';
el.style.boxSizing = el.style.mozBoxSizing = 'border-box';
el.style.height = "auto";
el.style.height = el.scrollHeight + 'px';
window.scrollTo(scrollLeft, scrollTop);
}
observe(el, 'input', resize);
resize();
});
}
init();
<textarea data-adaptheight style="padding: 7px;width: 100%;display: block;" rows="1" cols="40" placeholder="Your input">
</textarea>