Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function setSelectionRange is not working in Android browser

I am trying to do something like this in a directive in Angularjs. The problem is this works fine in system but when I check the same in Android phone it is failing to set the caret position. I checked on several blogs and website also, is there a solution for this in android device?

elem.bind("input", function(event) {
       var start = elem[0].selectionStart;
       if(start == 1 && event.currentTarget.value.charAt(start-1)==" "){
       var value = event.currentTarget.value.trim();
       event.currentTarget.value = value;
       elem[0].setSelectionRange(0, 0);
    }
}

And yes if I don't use setSelectionRange it moves the caret to the end.

like image 956
Gaurav Tyagi Avatar asked Mar 12 '26 19:03

Gaurav Tyagi


1 Answers

i had the same problem, i used this advice and it worked for me Why the setSelectionRange can't work on android 2.3 platform browser

try wrapping your "setSelectionRange" with "setTimeout with an interval of 0"

tha't should fix your problem.

for example:

   var start = elem[0].selectionStart;
   if(start == 1 && event.currentTarget.value.charAt(start-1)==" "){
   var value = event.currentTarget.value.trim();
   event.currentTarget.value = value;
   setTimeout(() => elem[0].setSelectionRange(0, 0),0);
}
like image 120
Noimang Avatar answered Mar 15 '26 09:03

Noimang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!