Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing text on-the-fly in contenteditable with pure jQuery

I have seen a few questions about this on StackOverflow, but it seems hard to find a jQuery-based solution. Hence, I would like to ask this question.

I would like to replace text on-the-fly inside a div with the attribute contenteditable="true".

I'm looking for a jQuery-based solution that will do the following:

  • Automatically replace written text on-the-fly (as you type)
  • Being able to continue writing (whilst the replacement is being done)

I looked at SC Editor (http://www.sceditor.com/), it seems like it does exactly that (for instance, if you try type :) it gets replaced by an emoticon.

I think a good start would be an array with all the elements to replace:

$.settings = {
    path: 'https://example.com/images/',
    emoticons: {
        ':(' : 'stupid.jpg',
        ':)' : 'smart.jpg',
    }
}

I have been unable to find good examples of this. Would be happy if somebody can share their thoughts and any code regarding this.

How would the replacement get done in the best possible way, with the above code?

like image 456
Robin Avatar asked Dec 19 '15 21:12

Robin


Video Answer


1 Answers

I found this. If you adjust it, it might suit your needs. It replaces { with {} and ( with () and the cursor ends up in the middle.

    <script type="text/javascript">
        $(document).ready(function () {
            $("#d").keypress(function (e) {
 
       
                    var charTyped = String.fromCharCode(e.which);
                    if (charTyped == "{" || charTyped == "(") {
                        // Handle this case ourselves
                        e.preventDefault();

                        var sel = window.getSelection();
                        if (sel.rangeCount > 0) {
                            // First, delete the existing selection
                            var range = sel.getRangeAt(0);
                            range.deleteContents();

                            // Insert a text node with the braces/parens
                            var text = (charTyped == "{") ? "{}" : "()";
                            var textNode = document.createTextNode(text);
                            range.insertNode(textNode);

                            // Move the selection to the middle of the text node
                            range.setStart(textNode, 1);
                            range.setEnd(textNode, 1);
                            sel.removeAllRanges();
                            sel.addRange(range);
                        }
                    }
         

            });
        });
    </script>
</head>

<body>
    <div id="d" contentEditable="true">....</div>
</body>
</html>
like image 113
Bindrid Avatar answered Sep 25 '22 14:09

Bindrid