Background:
I’m making a facebook wall-alike page, which will have many posts and you should be able to comment every post. And these textboxes, where you post type your comment in, should resize as in Facebook.
I have this code so far. It works but only in the FIRST textbox on the page, I would like it to work on every of them 🙂
Any chances to get it working for every textbox?
<script type="text/javascript">
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();
}
</script>
</head>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>
Can you provide sample code of a live page? As it stands, the javascript you’ve shown here only works on the single element identified with the ID of text; therefore, no matter how many textareas you have, the only element affected will one of the elements on the page with that ID — of which you should have only one, of course.
Approaching the code as it stands now, you need to change from
document.getElementByIdto something likedocument.getElementsByTagName('textarea')then loop over the result. Try the following:EDIT:
On review, among other things, your resize() function was only working on
textvariable as defined in the line immediately prior. Without totally refactoring your code, one way to get the functionality you want is the following:This isn’t optimal, but it should work.