Search code examples
javascriptjqueryiframewysiwygtext-editor

making wysiwyg text editor


I'd like to make my own text editor. I'm trying to follow the example of several other well established editors and use a hidden <textarea> and visible <iframe> combo.

I'm having trouble with the very first step of keying up the <iframe>. I can get execCommand to work on a contenteditable <div> to, e.g., make text BOLD but having trouble doing the same on the <iframe>.

Here's my HTML:

<html>
<button type="button" class="btn btn-bold">bold</button>
<textarea id="input" name="input" style="display: none;">Start typing..</textarea>
<iframe frameborder="0" src="javascript:true;" style="">  </iframe>
</html>

Here's my JavaScript:

    $(function() {
        var currentBtn;
        $("#input").focus(function() {
            currentBtn = this;
        });
        $(".btn").on( 'click', '.btn-bold', function(){
            var $this=$(this);
            if($this.hasClass("btn-bold")){ document.execCommand('bold', false, null);}
            $(currentBtn).contents().focus();
        });
    });

I know I need to perform the execCommand on the iframe document and not the parent document but just not sure how to do this. Currently, this code doesn't allow me to keyup the iframe so can't test the effect of the bold button.

Any thoughts would be greatly appreciated!


Solution

  • Use Rangy and wrap <b> around the selection to bold. You can perform other tasks with this method too.

    Demo: http://rangy.googlecode.com/svn-history/r511/trunk/demos/core.html

    Edit

    How to make iframe editable:

    window.frames[0].document.getElementsByTagName("body")[0].contentEditable = true;​