Search code examples
htmlwysiwyg

Make wysiwyg editor in html


I will make a wysiwyg1 editor for html. I've made a text area, but how can I make a wysiwyg editor for it? I would be easy if the text area implement html tags like snippet below, but it doesn't. How can I make this wysiwyg editor?

<textarea cols="30" rows="10">
    <h1>Title</h1>
    <hr/>
    <p>Some text</p>
    <ul>
        <li>a</li>
        <li>b</li>
        <li>c</li>
    </ul>
</textarea>

1 what you see is what you get


Solution

  • You can use following code...

     window.addEventListener("load", function(){
        //first check if execCommand and contentEditable attribute is supported or not.
        if(document.contentEditable != undefined && document.execCommand != undefined)
       {
           alert("HTML5 Document Editing API Is Not Supported");
        }
        else
        {
            document.execCommand('styleWithCSS', false, true);
        }
    }, false);
    
    //underlines the selected text
    function underline()
    {
        document.execCommand("underline", false, null);
    }
    
    //makes the selected text as hyperlink.
    function link()
    {
        var url = prompt("Enter the URL");
        document.execCommand("createLink", false, url);
    }
    
    //displays HTML of the output
    function displayhtml()
    {
        //set textContent of pre tag to the innerHTML of editable div. textContent can take any form of text and display it as it is without browser interpreting it. It also preserves white space and new line characters.
        document.getElementsByClassName("htmloutput")[0].textContent = document.getElementsByClassName("editor")[0].innerHTML;
    }
    .editor
    {
        width: 500px;
        height: 500px;
        background-color: yellow;
    }
    <button onclick="underline()">Underline Text</button>
    <button onclick="link()">Link</button>
    <button onclick="displayhtml()">Display HTML</button>
    <!-- Make it content editable attribute true so that we can edit inside the div tag and also enable execCommand to edit content inside it.-->
    <div class="editor" contenteditable="true" spellcheck="false">
        This is the text editor
    </div>
    
    <div class="codeoutput">
        <!-- <pre> tags reserves whitespace and newline characters. -->
        <pre class="htmloutput">
        </pre>
    </div>

    Reference: labs.qnimate.com/wysiwyg-editor