Search code examples
javascripthtmlexeccommand

Document.execCommand not updating currently active element


I have a pre tag which encloses an input tag. There is a paste event listener tied to the pre tag.

$(function() {
if (document.querySelector('pre[contenteditable="true"]') != null) {
	    	document.querySelector('pre[contenteditable="true"]').addEventListener("paste", function(e) {
	    		e.preventDefault();
          //alert("test");
	    		var text = e.clipboardData.getData("text/plain");
	    		document.execCommand("insertHtml", false, text);
	    	});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="previewEmailBody" class="blurbBody" placeholder="Reply" style="display:block" contenteditable="true">Testing
<input class="emailBodyToken" name="[Test]" size="54" value="[Test]" >
Testing</pre>

Now - if I click on input element and do text paste - it is not updating the input element instead it is updating the text in the pre element.

The above behavior was observed only in firefox. In chrome, it updates the input element as expected. I want the same behavior in firefox as well. Do suggest a way around this.

Working example: https://jsfiddle.net/5mwk0bxc/7/


Solution

  • You need to let the event happen if it is targeted towards a input element.

    $(function() {
    if (document.querySelector('pre[contenteditable="true"]') != null) {
                document.querySelector('pre[contenteditable="true"]').addEventListener("paste", function(e) {
            if (e.explicitOriginalTarget.tagName !== "INPUT")
                    {
              e.preventDefault();
              //alert("test");
                    var text = e.clipboardData.getData("text/plain");
                    document.execCommand("insertHtml", false, text);
                }
        });
    }
    });
    

    Updated JS fiddle

    https://jsfiddle.net/5mwk0bxc/9/

    Working