Search code examples
javascriptcursorwhitespacespaceexeccommand

javascript - Why do I get a   if I script  ?


I having hard time to insert a single space at the end of my </span> in a document.execCommand().

document.execCommand("insertHTML", false, "<span class='own-class2'>"+"Test"+"</span>");

The reason behind this is I want the cursor to be outside the <span> after having made the insertion.

Here is a simple jsFiddle to show you what I mean: jsFiddle In that example, if you click the image and then write something, the text will be green. That means the text is still inside the span.

So What I want is to insert a normal space after </span>.

What I have already tried:

  • a space like this '</span> ' -> I get no space in Chrome.
  • a space like this '</span>&#32;' -> I get </span>&nbsp; in Chrome

So my question is how to add a single space in order to get a result equivalent to this '</span>&#32;' or '</span> ' and not '</span>&nbsp;' ?

WHAT I GET ON THE INSPECTOR : https://ibb.co/cqCW2x

if I do :

document.execCommand("insertHTML", false, "<span class='own-class2'>"+"Test"+"</span>&#32;");

Solution

  • Maybe you could use the zero width no break space character (invisible character) : \uFEFF.

    The advantage of this solution is it does not create an (maybe?) unwanted visible space after the span

    function Test() {
    document.execCommand("insertHTML", false, "<span class='own-class2'>"+"Test"+"</span>\uFEFF");
    }
    #textBox {
    	width: 540px;
    	height: 200px;
    	border: 1px #000000 solid;
    	padding: 0;
    	overflow: scroll;
    }
    .own-class2 {color:green;}
    <div id="toolBar">		
    	<button height="20px" onclick="Test()" >insert a span</button>
    </div>
    <div id="textBox" class="textbox" contenteditable="true"></div>