Search code examples
javascriptexeccommand

execCommand: change everything from the current line down?


I don't know how this kind of editing is called, but I've seen it somewhere before. Lets say you have an article with a heading, body and footer. In your own WYSIWYG editor, you have three buttons for each article section, or maybe a dropdown with those options.

When you paste the content of the article into the editor, you want to use the buttons one after the other to divide the content into the sections you want. First, you click on the line you want to define as the heading. You click on any part of the line, doesn't matter. Now you click the heading button, and it defines the line where you currently are, and anything below it, as the heading. Now you click on the line you want to define as the body, and click the body button. Again, everything on the line, and below it, is defined as body. You do the same for footer.

Is something like that possible with execCommand?


Solution

  • The open-source library wysiwyg.js takes cares of the heavy work with contenteditable divs, etc and allows you to create a frontend that suits your needs. You only need to write the code for the functions you need and you can put your own CSS styling on top of it. I wrote some example code using the jQuery version of library below, but there's plenty of information and examples in the documentation linked above. They also do have a pure JavaScript variant if that's easier for you to work with.

    <button id="header">Header</button>
    <button id="footer">Footer</button>
    <textarea id="editor">Lorem ipsum dolor sit amet</textarea>
    
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="http://path/to/wysiwyg.min.js"></script>
    <script src="http://path/to/wysiwyg-editor.min.js"></script>
    
    <script>
    $(document).ready(function () {
        var editor = $("#editor").wysiwyg();
    
        $("#header").click(function () {
            editor.wysiwyg("shell").bold().fontSize(30);
        });
    
        $("#footer").click(function () {
            editor.wysiwyg("shell").italic();
        });
    });
    </script>
    

    If you want to keep it simpler than that, Quill is a good option. It's still not as "heavy" as CKEditor and has an elegant interface. It also has built-in functionality for styling presets, such as headers and footers. This functionality also doesn't require you to highlight the line(s) you want to format, unlike wysiwyg.js. Though, this could be added into a wysiwyg.js solution with a custom function similar to this.