Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Auto-Expanding Textarea #11

Open
gingerchew opened this issue Aug 20, 2020 · 0 comments
Open

Adding Auto-Expanding Textarea #11

gingerchew opened this issue Aug 20, 2020 · 0 comments

Comments

@gingerchew
Copy link

I noticed at the bottom of the readme there was a todo to add the auto-expanding textarea. I thought I might take a crack at it:

/* CSS from the article in the TODO */
textarea {
	min-height: 5em;
	max-height: 50vh;
	width: 100%;
}
(function() {

	var autoExpand = function(field) {
		field.style.setProperty('height', 'inherit'); // supported back to IE 9
		var computed = window.getComputedStyle(field),
			height = parseInt(computed.getPropertyValue('border-top-width'), 10)
					 + parseInt(computed.getPropertyValue('padding-top'), 10)
					 + field.scrollHeight
					 + parseInt(computed.getPropertyValue('padding-bottom'), 10)
					 + parseInt(computed.getPropertyValue('border-bottom-width'), 10);
		
		field.style.setProperty('height', height + 'px')
	}

	document.addEventListener('input', function(event) {
		if (event.target.tagName !== 'TEXTAREA') return; // removed `.toLowerCase()`
		autoExpand(event.target)
	}, false)

})();

I tried to use the same sensible patterns I've seen in your blog posts. I did opt for using .setProperty() instead of el.style.prop = 'value';. It's got support back to IE 9, and it matches the same syntax as the .getPropertyValue(). I also removed the .toLowerCase().

Hopefully this helps, it's one of my favorite utilities and I'd love for more people to know about it 🙂

Utility for parsing multiple computed properties
// Just for fun :)
var parseStyles = function() {
	var args = Array.prototype.slice.call(arguments),
		out = 0;
	for (var i = 1; i < args.length; i++) {
		out += parseInt(args[0].getPropertyValue(args[i]), 10)
	}
	return out
}
parseStyles(window.getComputedStyles(field), 'border-top-width', 'padding-top', 'padding-bottom', 'border-bottom-width');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant