简体   繁体   中英

Focus textarea with caret after text in Android browser

I am currently writing a simple webapp to view tweets in the Android browser. I am using this code to focus the caret after the current text:

var oldContent = document.tweetBox.tweet.value;
document.tweetBox.tweet.value = '';
document.tweetBox.tweet.focus();
document.tweetBox.tweet.value = oldContent + to;

This code works flawlessly in Chrome, Fluid, Opera, Firefox en Safari.
The weirdest part is that the cursor starts blinking AFTER the 'to' text if I use my hardware keyboard but the text that I enter starts where I was typing before the JS above was executed.
If I use the soft keyboard the text entering starts at the start of the textarea.

ps The javascript is part of a suggestion for followers, so if you start typing @gn it will suggest @gnur_nl in a seperate div and when you press enter this entry is chosen.

Update: This behaviour seems to be the result of a browser bug, a bug report has been filed .

Sounds like a browser bug. Try setting the caret position manually:

var textArea = document.tweetBox.tweet, oldContent = textArea.value;
textArea.value = oldContent + to;
textArea.focus();
textArea.selectionStart = textArea.selectionEnd = textArea.value.length;
setCaret = function(obj,pos) {
    // IE Support
    if (document.selection) { 

        // Set focus on the element
        obj.focus ();

        // Create empty selection range
        var oSel = document.selection.createRange ();

        // Move selection start and end to 0 position
        oSel.moveStart ('character', -obj.value.length);

        // Move selection start and end to desired position
        oSel.moveStart ('character', pos);
    }

    //standard browsers
    else if (obj.selectionStart || obj.selectionStart == '0') {
        obj.selectionStart = pos;
        obj.selectionEnd = pos;
        obj.focus ();
    }
};

and setting to the right positions

setCaret(document.getElementById("area"),document.getElementById("area").value.length);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM