E
E
Eugene Ordinary2017-04-27 12:39:05
JavaScript
Eugene Ordinary, 2017-04-27 12:39:05

Chrome doesn't update cursor position if it is moved by Backspace?

There is a function that inserts text or a character into a textarea field at the cursor position. Everything works great. But in Chrome, the text is inserted in the place where the cursor was before it was shifted to the left by Backspace. If the cursor is placed with the mouse or moved with the arrows to the left, right, then it works fine. Apparently, Chrome does not update the cursor position only if it is moved by Backspace. Checked in Firefox. There are no glitches.
The code looks like this. The code seems illogical, because I simplified the function, in fact, paired tags can also be inserted around the selected text, but the essence of the glitch does not change.

function str_insert( str, ta ) //ta = textarea
{
  ta.focus();
  
  if( typeof(ta.selectionStart) != "undefined" )
  {
    var start = ta.selectionStart;
    var end = ta.selectionEnd;
    var slen = end-start; 
    var scrollTop = ta.scrollTop;

    var rs = (ta.value.substr(start, slen)) + str;
    ta.value = ta.value.substr(0,start) + rs + ta.value.substr(end);
    
    ta.setSelectionRange(start+rs.length, start+rs.length);
        
    ta.scrollTop = scrollTop;
    ta.focus();
  }
}

Is there really such a glitch or is it a mistake somewhere?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question