Last active
August 26, 2023 17:16
-
-
Save i-havr/6b8e6f39da421360c6c054c9d2765d61 to your computer and use it in GitHub Desktop.
This code allows you to create auto-expanding textarea field without un ugly expanding-corner :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getScrollHeight(elm) { | |
var savedValue = elm.value; | |
elm.value = ""; | |
elm._baseScrollHeight = elm.scrollHeight; | |
elm.value = savedValue; | |
} | |
export const onExpandableTextareaInput = ({ target: elm }) => { | |
if (!elm.classList.contains("autoExpand") || !elm.nodeName == "TEXTAREA") | |
return; | |
var minRows = elm.getAttribute("data-min-rows") | 0, | |
rows; | |
!elm._baseScrollHeight && getScrollHeight(elm); | |
elm.rows = minRows; | |
rows = Math.ceil((elm.scrollHeight - elm._baseScrollHeight) / 16); | |
elm.rows = minRows + rows; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.autoExpand { | |
resize: none; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { onExpandableTextareaInput } from "./auto-expanding-textarea"; | |
import "./index.css"; | |
document.addEventListener("input", onExpandableTextareaInput); | |
export default function SomePage() { | |
const handleChange = () => { | |
console.log("The value was changed!")} | |
return ( | |
<form> | |
<label> | |
Поле 1 | |
<textarea | |
className="autoExpand" | |
type="text" | |
rows={2} | |
data-min-rows={2} | |
placeholder="Поле обов'язкове" | |
name="name" | |
value={name} | |
onChange={handleChange} | |
autoFocus | |
/> | |
</label> | |
</form> | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment