3

I am trying to achieve project and I must do a WYSIWYG editor in JavaScript. I can't use an existing editor because I need use my plugins (for example a colorPicker or imagePicker).

For now I have this HTML:

<div class="K_editor" id="idExample">
   <div class="K_links">
      <div class="K_editor_link K_editor_linkBold">B</div>
      <div class="K_editor_link K_editor_linkItalic">I</div>
      <div class="K_editor_link K_editor_linkUnderline">U</div>
   </div>
   <iframe width="696" height="212" frameborder="0" src="js/myEditor_iFrame.php">
      <html>
         <head/>
         <body>
            <div id="contentIframe" contenteditable="true">
               This is a test code, with <strong>bold</strong> text and  <em>italic</em> text.
            </div>
         </body>
      </html>
   </iframe>
   <input type="submit"/>
</div>

On event click on .K_editor_link, a function is open with arguments:

  • tagStart (example <u>, or <span style="color:#AB1;">)
  • tagEnd (example </u>, or </span>)
  • id (here idExample)

I know get a Selection on Textarea but setSelectionRange(), .selectionStart and .selectionEnd are only for textbox (XUL), input (XHTML) or textarea (XHTML).

What can I do for do that?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
CactO_o's
  • 31
  • 1
  • 3
  • The fact that you must use your own plugins don't really force you to write a WYISWYG editor by yourself. CKEditor and TinyMCE allow to use your own plugins, in fact they are structured as a group of plugins around a core. – AlfonsoML Dec 10 '11 at 18:27

1 Answers1

1

This is the code I use. I can not take credit for it since I found it here on SO a couple of months ago. Don't remember where. Hope it works out for you.

function getSelectionHtml() 
{
    var html = "";

    if (typeof window.getSelection != "undefined") 
        {
        var sel = window.getSelection();
        if (sel.rangeCount) 
            {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;

}

Code is from this question: window.getSelection return html

Community
  • 1
  • 1
Adrian
  • 25
  • 6