user3722851 user3722851 - 3 months ago 30
Javascript Question

Javascript mouse start position

I am using CkEditor in asp.net mvc.

View:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="~/Content/ckeditor/ckeditor.js"></script>

@Html.TextArea("editor", new { @class = "ckeditor", @id = "aboutme" })

<button type="submit" class="btn btn-primary" id="AddText">Add Text</button>


If i click to button , i want to set any text inside of Html.Textarea where mouse clicked.

As instance,

I have a value below in TextArea

My Name İs xxxx


If i click to between "My" and "Name" after that if i click to button , i want to set value(text) between My and Name above .

How can i do this , i hope you understand my bad english.

Thanks.

Answer

PLease chcek below URL , it can help you to get your answer

$(function () {

    $('input#insertPattern').click(function () {
        //alert('clicked me');
        insertEmoticonAtTextareaCursor('insertPattern', ':)');
    });

    function insertEmoticonAtTextareaCursor(ID, text) {
        //var txtarea = document.getElementById(areaId);

        var txtarea = $("#" + ID).next('textarea')[0];
        var scrollPos = txtarea.scrollTop;
        var strPos = 0;
        var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
            "ff" : (document.selection ? "ie" : false));
        if (br == "ie") {
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart('character', -txtarea.value.length);
            strPos = range.text.length;
        } else if (br == "ff") strPos = txtarea.selectionStart;

        var front = (txtarea.value).substring(0, strPos);
        var back = (txtarea.value).substring(strPos, txtarea.value.length);
        txtarea.value = front + text + back;
        strPos = strPos + text.length;
        if (br == "ie") {
            txtarea.focus();
            var range = document.selection.createRange();
            range.moveStart('character', -txtarea.value.length);
            range.moveStart('character', strPos);
            range.moveEnd('character', 0);
            range.select();
        } else if (br == "ff") {
            txtarea.selectionStart = strPos;
            txtarea.selectionEnd = strPos;
            txtarea.focus();
        }
        txtarea.scrollTop = scrollPos;
    }

});

HTML

<div id="100000000">
    <input id="insertPattern" type="button" value="insert pattern" />
    <textarea class="chatMessengerFooterTextArea">insert some text into this string</textarea>
</div>

DEMO