user717166
user717166

Reputation: 680

Can DIV replace TextArea

As we know can set contenteditable in DIV to allow editable. It can make same like Textarea.

However there's the most big different are the "content copy and paste" to DIV and Textarea.

DIV is allow html/plain but Textarea only serve plain text.

Below are the method to solve those problem:-

Method 1 - Direct using window.clipboardData.getData('Text') ( will prompt for asking permission).  

Problem : Mozilla and chrome are not support clipboarddata.

Method 2 - Using flash.

Problem : Flash v.10 has upgraded to new rules which cannot get clipboarddata without user first initialize.

Method 3- Using "onpaste" event. When data paste on div -> Set focus on hidden textarea -> Get value from hidden textarea and set into div by using setTimeout -> clear hidden textarea.

Problem : The timing set value to hidden textarea are not consistent.

I have saw google was doing well on this.

For IE , use clipboarddata.

For Mozilla,others (not support html5) - Anyone know how google done it ?

Hint: use iframe designmode ?

For Chrome (support html5) - Just set DIV to Contenteditable="plaintext-only".

Upvotes: 0

Views: 1233

Answers (1)

Roland Bouman
Roland Bouman

Reputation: 31961

The trick that I use for this kind of thing is to have an offscreen <textarea>, which is not visible to the user.

The textarea is focussed and has a keyboard handler that notices whether the user is typing in the textarea. As I detect the user is typing, I grab the value of the textarea and dump it in the div.

This is the basic idea. You'll need a bit more to get the look and feel right:

  1. you can't just hide the textarea with display:none or visibility:hidden because that will generally make it insensitive to typing and events too. So you need to make it really small and position it outside the screen, or stack it behind some other element.
  2. you're going to have to detect whether the textarea blurs and decide if you need to refocus it.
  3. You'll want a click handler on the div so that if people click the div you can focus to the textarea instead so people can start typing again.

The nice thing about this approach is that general keyboard handling, like ctrl+cursor, and cut+paste etc. all work exactly as expected without having to code that yourself - you're just piggybacking on the existing functionality of the textarea.

Here's an example of how this works:

http://js1k.com/2012-love/demo/1168

(A javascript shell)

Upvotes: 1

Related Questions