开发者

Resizable Textarea Like on SO using Vanilla Javascript

开发者 https://www.devze.com 2023-01-16 00:22 出处:网络
I\'m basically looking to duplicate the functionality of the draggable resize function of the textareas here on SO.

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:

  1. Remove targeted textarea from the DOM

  2. Create a div

  3. Put the removed textarea into the newly created div and style it so it always takes all available area of the div

  4. Add an element for the drag handle and style it (probably also a div)

  5. Attach onmousedown and onmousemove event handlers to the drag handle element and reinstert the wrapper div into the DOM

  6. On mousedown event, record the mouse coordinates

  7. On mousemove event get the current mouse coordinates and calculate the delta with the previously memorised coordinates

  8. Set 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消