Reputation: 149
I have a textarea
of fixed width
and height
, I don't want to resize textarea
neither I want to add scroller to it, when text greater than it's height is added. I want it to restrict adding further text.
Note: maxLength
property will not solve my problem, as fontSize
and fontFamily
can be anything, so I don't know maxLength
value, only width
and height
of textarea
in pixels
Upvotes: 1
Views: 232
Reputation: 149
Thanks for giving me the hint. I was looking for a solution in React, but the solution in Jquery helped too. So,I am writing solution to my own question in react
enter code here
onPaste(ev) {
ev.stopPropagation();
ev.preventDefault();
const elem = this.textarea;
const clipboardData = ev.clipboardData || window.clipboardData;
const pastedData = clipboardData.getData('Text');
let index = elem.selectionStart;
for (let i=0; i<pastedData.length; i++) {
const strChar = pastedData.charAt(i);
elem.value = elem.value.slice(0, index) + strChar + elem.value.slice(index);
if (this.textarea && elem.clientHeight < elem.scrollHeight) {
elem.value = elem.value.slice(0, index) + elem.value.slice(index + 1);
break;
}
index = index + 1;
}
}
handleTextareaChange(ev) {
const elem = this.textarea;
if (elem.clientHeight < elem.scrollHeight) {
elem.value = elem.value.slice(0, elem.selectionStart - 1) + elem.value.slice(elem.selectionStart);
}
}
React JSX
<textarea
title={this.props.tooltip}
onChange={this.handleTextareaChange}
onPaste={this.onPaste}
ref={textarea => {
this.textarea = textarea;
}}
style={{overflowY: "hidden"}}
/>
Upvotes: 0
Reputation: 84
Try This:
$("#test1").on("keypress", function(event) {
if(($(this).prop("scrollHeight")) > $(this).innerHeight()){
return false;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="test1" rows="2"></textarea>
Upvotes: 2
Reputation: 1174
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea rows="3" onkeyup="myFunction(this)">
a
</textarea>
<script>
function myFunction(textarea) {
if (textarea.scrollHeight > textarea.clientHeight) {
console.log('visible')
} else {
console.log('not visible');
}
}
</script>
</body>
</html>
Upvotes: 2