Resizable Textarea Like on SO using Vanilla Javascript
I'm basically looking to duplicate the functionality of the draggable resize function of the textareas here on SO.
I know SO uses the开发者_StackOverflow社区 jQuery plugin TextAreaResizer to accomplish this, but I want to use straight vanilla javascript so that I can learn how it actually works.
Well, here are the basic steps you will need to take:
Remove targeted
textarea
from the DOMCreate a
div
Put the removed
textarea
into the newly createddiv
and style it so it always takes all available area of thediv
Add an element for the drag handle and style it (probably also a
div
)Attach
onmousedown
andonmousemove
event handlers to the drag handle element and reinstert the wrapperdiv
into the DOMOn
mousedown
event, record the mouse coordinatesOn
mousemove
event get the current mouse coordinates and calculate the delta with the previously memorised coordinatesSet the wrapper
div
size to its current size PLUS the deltas that you calculated (when deltas are negative, the size will reduce)
That's the basic steps you need to take, but there is a bit of detail that you will need to work out.
Well, why don't you just grab the plugin and look at its source code:
http://plugins.jquery.com/project/TextAreaResizer
?
I know you mentioned you want to use "vanilla" JavaScript, but if you are trying to learn the language itself you don't lose anything using jQuery. jQuery provides an abstraction to JS, which is a real PITA to get working across browsers, mainly because of inconsistencies in the DOM implementation.
If you are brave enough, you can use just JS - but that will require significantly more work for little added learning benefit. Don't tell I didn't warn you when you get headaches.
It's good to want to learn how to work without hand-holding from a third-party library, but that doesn't mean you can't learn from it. jQuery is just a library of straight vanilla Javascript — there is no other language mixed in.
There seems to be this pervasive notion that there is somehow "jQuery Javascript" and "vanilla Javascript," but for the most part, jQuery is just a library of prewritten code that handles a lot of the more annoying parts for you. You can figure out how to do it without depending on jQuery by looking at how jQuery does it and writing equivalent code yourself. The general techniques will mostly be the same.
The biggest differences you'll usually have in your custom code is that you probably won't want to recreate the whole selector engine (which lets you write things like $("div.foo")
to find divs with the class foo). Instead, you should substitute element selection and creation logic more appropriate for your specific case.
精彩评论