5

Here's one usecase that has been baffling me. When I select some text and paste it in any of Google's applications like docs or notebook, it somehow manages to paste the text with its original formatting and sometimes images itself. Can someone tell me how to do this using javascript/jquery?

Edit: One more scenario that I am looking at is say designing a server-based copy/paste mechanism.

Legend
  • 113,822
  • 119
  • 272
  • 400

1 Answers1

7

You can use contenteditable to do this:

<div contenteditable="true">Stuff pasted in here will retain their original HTML</div>

Here's a simple demo for this: http://jsfiddle.net/AA3Kq/


Regarding your second scenario, you'll want to look at JavaScript's selection API. I'm not an expert on this, but here's some places where you can get started on:

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
  • @Yi Jang: +1 Thanks. But what if I want to send this content with its original formatting to a remote server, say, to enable server-based copy/pasting. Is it still possible to do some fiddling with js? – Legend Feb 20 '11 at 03:50
  • @Legend I'm not entirely sure how `contenteditable` fields interact with forms, but it isn't very hard to test yourself. Worse come to worse you can always insert the content of the field into a hidden input field on submit using JavaScript – Yi Jiang Feb 20 '11 at 03:54
  • @Yi Jang: Oh your solution works perfectly for one of the scenarios. For the other one where let's say I am creating a small bookmarklet that grabs the currently selected text and sends it to the remote server, I am looking for a way to preserve the formatting. – Legend Feb 20 '11 at 03:56
  • @Yi: conteneditable just lets you change the contents of a block on a page. To submit changes to the server, you need some javascript to extract the contents of that block and submit it. Simply having an editable block within a form won't turn that block into a form field - you have to explictly extract and submit yourself. – Marc B Feb 20 '11 at 03:59