Search code examples
javascripthtmleditorwysiwyg

Change the line height of the selected text with Javascript


I am trying to program my own WYSIWYG editor as a summer project. I am trying to implement the line height function that controls(single spacing, double spacing, etc). I have created the dropdown that will allow users to select between the types of spacing. However, I cannot seem to get the right Javascript, because the selected text does not change in line spacing at all no matter which option I choose. Can someone please take a look at my Javascript and tell me where I went wrong? If possible, can you give me the correct code for the Javascript so I can refer off of it? Thank you!

HTML(working):

 <select id="lineHeight" onchange="spacing(this)">
                                <option value="20px">20px</option>
                                <option value="80px">80px</option>
                                <option value="100px">100px</option>
                                <option value="200px">200px</option>
                            </select>

Javascript(not working)

function spacing(sel) {
        var text = editor.document.getSelection();
        text.style.lineHeight = sel.value;
    }

Solution

  • If I understand what you're trying to do, perhaps this will work for you:

    function changeStyle( property, value ) {
        if ( window.getSelection().rangeCount ) {
            var range = window.getSelection().getRangeAt( 0 ),
                contents = range.extractContents(),
                span = document.createElement( 'span' );
    
            span.style[ property ] = value;
            span.appendChild( contents );
            range.insertNode( span );
            window.getSelection().removeAllRanges()
        }
    }
    #editor {
        width: 350px;
        max-height: 100px;
        padding: 20px;
        overflow-y: auto;
        background-color: #efefef;
        border: 1px solid #ddd
    }
    <p>
        <label for="lineHeight">Line Height: </label>
        <select id="lineHeight" onchange="changeStyle('line-height', this.value)">
            <option value="20px">20px</option>
            <option value="80px">80px</option>
            <option value="100px">100px</option>
            <option value="200px">200px</option>
        </select>
        <button onclick="changeStyle('font-weight', 'bold')">Bold</button>
        <button onclick="changeStyle('font-style', 'italic')">Italic</button>
        <button onclick="changeStyle('color', 'red')">Color</button>
        <button onclick="changeStyle('background-color', 'yellow')">Background</button>
    </p>
    
    <div id="editor" contenteditable>Change the line height of the selected text with Javascript:<br>Please note that this example should be completed.</div>