Created
February 12, 2020 03:01
-
-
Save tomhodgins/cc4767befc96e9e35a30fe0ffd3f78f6 to your computer and use it in GitHub Desktop.
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
<input> | |
<textarea></textarea> | |
<style> | |
input { | |
--auto-expand: width; | |
} | |
textarea { | |
--auto-expand: height; | |
} | |
</style> | |
<script type=module> | |
import {process, property} from 'https://unpkg.com/cssomtools' | |
// Collect selectors of rules containing an --auto-expand property | |
const selectors = [] | |
// Process CSSOM for rules containing an --auto-expand property | |
process(property('--auto-expand'), rule => { | |
selectors.push(rule.selectorText) | |
}) | |
// Listen to input, paste, and blur events on all elements matching selectors | |
document.querySelectorAll(selectors.join(',')).forEach(tag => | |
['input', 'paste', 'blur'].forEach(evt => | |
tag.addEventListener(evt, event => { | |
// Supported features are: width, height, both | |
const features = { | |
width: tag => { | |
const computed = getComputedStyle(tag) | |
tag.style.width = 'inherit' | |
const width = parseInt(computed['border-left-width']) | |
+ parseInt(computed['padding-left']) | |
+ tag.scrollWidth | |
+ parseInt(computed['padding-right']) | |
+ parseInt(computed['border-right-width']) | |
tag.style.width = '' | |
return tag.style.width = `${width}px` | |
}, | |
height: tag => { | |
const computed = getComputedStyle(tag) | |
tag.style.height = 'inherit' | |
const height = parseInt(computed['border-top-width']) | |
+ parseInt(computed['padding-top']) | |
+ tag.scrollHeight | |
+ parseInt(computed['padding-bottom']) | |
+ parseInt(computed['border-bottom-width']) | |
tag.style.height = '' | |
return tag.style.height = `${height}px` | |
}, | |
both: tag => features.width(tag) + features.height(tag) | |
} | |
// Computed this tag's size based on value of --auto-expand property | |
features[ | |
window.getComputedStyle(event.target).getPropertyValue('--auto-expand').trim() | |
]( | |
event.target | |
) | |
}) | |
) | |
) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment