Setting a Range for a Textarea based on User Input
<p>I have a textarea and I'm trying to check if someone enters <strong>{{link</strong>  that I can have a modal pop up to let them complete some information.  </p>

<p>What I have now is that if someone enters the letter k, it will go back 6 characters and then determine if the text matches <strong>{{link</strong> </p>

<p>But I'm having a problem in setting setting the start and end points for the range. I think that  the problem is with identifying the node, but I'm not sure.</p>

<p>Mainly when someone enters a the letter "k", I'm just trying to go back to check if they had typed: <strong>{{link</strong>  and if they did, it would launch a modal.  </p>

<p>This is what I have that isn't working at the part where I'm trying to set the range and get the selection.</p>

<pre><code>$(document).on('keyup', 'textarea', function(e) {

    if (e.keyCode == 75) {

    var end = $('textarea').getCaretPosition();
    var start = end - 6;
    var node = $(this).get(0);

    var range = document.createRange();
    range.setStart(node, start);
    range.setEnd(node, end);

    var selection = range.toString();

        if( selection == '{{link' ){    
            // we'll launch a modal here
        }
    }

});


    $.fn.getCaretPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
</code></pre>

<p>This generates the error: Uncaught Error: INDEX_SIZE_ERR: DOM Exception 1 at range.setStart(node, start);</p>
