I ran into an expanding textArea on code pen, https://codepen.io/vsync/pen/frudD It appears to work well. The code that drives it is:
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
Which I translated into Javascript as the following. Which also appears to be working well, and I do not get any errors on the console:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<textarea class='autoExpand' rows='3' data-min-rows='3' placeholder='Auto-Expanding Textarea'></textarea>
<script>
'use strict';
function handler_focusin(e){
let savedValue = e.target.value;
e.target.value = '';
e.target.baseScrollHeight = e.target.scrollHeight;
e.target.value = savedValue;
}
function handler_input(e){
let minRows = e.target.getAttribute('data-min-rows')|0, rows;
e.target.rows = minRows;
rows = Math.ceil((e.target.scrollHeight - e.target.baseScrollHeight) / 16);
e.target.rows = minRows + rows;
}
let els = document.getElementsByClassName("autoExpand");
[...els].forEach( el => {
el.addEventListener('focusin', handler_focusin);
el.addEventListener('input', handler_input);
})
</script>
</body>
Questions:
Look at the first statement in the function_handler (both in the JS version and the corresponding
jQuery). There is an undeclared symbol 'rows' sitting there. There is a comma operator, so I would expect row to be evaluated, but there is no error in the console. Then two statements down rows is assigned to, again no declaration and no error.Also, why bother with the comma operator as rows is evaluated last and returned?
In that same statement, I gather that 'data-min-rows' is a potentially programmer defined attribute, so unless that has been added, it will return undefined. I suppose then the the
bitwiseOR withzerothat follows it, is to take precedence and that this returns zero.Correct?
In jQuery apparently 'this' is the same as e.target. (found that in a couple of references). However, when I translated the code I missed changing a 'this' to an e.target, and it still worked.
Is
thisalso reliablye.targetin aJavascriptevent handler? (The references I found from searches all appear to be talking about jQuery.)The
jQuerycode also assigns the event handlers totextarea.autoExpandbut 'textarea' is not an event name. What is that doing? Is there something it corresponds to in Javascript?