Detect when “cursor position inside input change” in jQuery?

后端 未结 2 1187
野趣味
野趣味 2020-12-05 19:21

I\'m using a plugin called jQuery TextRange to get the position of cursor inside a input (in my case, a textarea) and set the position too.

But now I have one thing

相关标签:
2条回答
  • 2020-12-05 20:00

    I needed something like this myself, so based on @RenatoPrado solution I've created a jQuery extension (it's on npm - jquery-position-event).

    To use it you can add standard event:

    var textarea = $('textarea').on('position', function(e) {
       console.log(e.position);
    });
    

    and if you want the initial value you can use:

    var textarea = $('textarea').on('position', function(e) {
       console.log(e.position);
    }).trigger('position');
    

    The event also have useful column and line properties.

    0 讨论(0)
  • 2020-12-05 20:24

    No, there is no event like "cursor position changed".

    But if you want to know if the cursor position changed, you can do something like this: tested with jquery 1.7, i tested in Ie8 and chrome

    var last_position = 0;
    $(document.ready(function () {
        $("#my_input").bind("keydown click focus", function() {
            console.log(cursor_changed(this));
        });
    });
    

    the console.log will return if the cursor have changed

    function cursor_changed(element) {
        var new_position = getCursorPosition(element);
        if (new_position !== last_position) {
            last_position = new_position;
            return true;
        }
            return false;
    }
    
    function getCursorPosition(element) {
        var el = $(element).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;
    }
    
    0 讨论(0)
提交回复
热议问题