8

I want to copy/paste html from websites and store them in mysql database. To do this I have checked out CKEditor which allows me to paste html, even word documents and it generates html code for it. Since all I want is to "generate" the pasted data as html, instead of using a full wysiwyg editor like CKEditor, I want to write some code (perhaps with jquery) to convert the pasted data to have html tags and formatting.

To achieve this functionality, what do these online editors do? How do they convert the clipboard data to html code? Why do I get only text when I paste html formatted text or divs or buttons to this textarea here and images and properly sized divs on wysiwyg editors?

Do the editors access the clipboard data and manipulate it? Does clipboard save formatting data in an organized manner allowing the "CKEditor" or others to manipulate it?

Can this be done with jQuery? Or do we need server-side code as well?

If you can shed some light on this subjects I would appreciate it. I only want to know the method so that I can write appropriate code for it.

For reference: http://ckeditor.com/demo

Logan
  • 10,649
  • 13
  • 41
  • 54
  • I suppose you could paste HTML into an element with `contenteditable="true"` and get the inner HTML from that with a bit of script. – Tim M. Nov 29 '12 at 02:01

1 Answers1

6

Here's a crude demo which works in Chrome, IE9 and Safari: http://jsfiddle.net/SN6PQ/2/

<div contenteditable="true" id="paste-target">Paste Here</div>​

$(function(){
    $("#paste-target").on("paste", function(){
        // delay, or else innerHTML won't be updated
        setTimeout(function(){

            // option 1 - for pasting text that looks like HTML (e.g. a code snippet)
            alert($("#paste-target").text());

            // option 2 - for pasting actual HTML (e.g. select a webpage and paste it)
            alert($("#paste-target").html());
        },100);
    });        
});​

Not sure if this is what you are after, but it alerts HTML on paste. Keep in mind that a content editable element may change the markup on paste.

Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • 2
    Thank you, this is exactly what I was after... so there is a paste event for jquery... most interesting! – Logan Nov 29 '12 at 02:07
  • Glad it works. There are a variety of questions around pasting, in case you want to refine my example, e.g. http://stackoverflow.com/questions/686995/jquery-catch-paste-input?lq=1 – Tim M. Nov 29 '12 at 02:08
  • Ah, I've actually seen that post while I was researching, but failed to understand that it also pasted as html. Btw I have looked up the compatibility for paste event for javascript and here it is: [cutcopypaste](http://www.quirksmode.org/dom/events/cutcopypaste.html) – Logan Nov 29 '12 at 02:20