Getting caret position in IE works in one scenario, doesn't in another
<p>I have an <code>input</code> element in HTML markup as below:</p>

<pre><code>&lt;input type="text" name="s" id="s" value="" /&gt;
</code></pre>

<p>I am changing the characters entered in this input element with Urdu ones (like a mini virtual keyboard), by using jQuery's <code>keypress</code>:</p>

<pre><code>$("#s").keypress(function(e) {
    var pos = getCaretPos('s');
    // key-mapping logic here
});
</code></pre>

<p>I also have some buttons that help a user enter their desired Urdu character by clicking on a respective button. Thus:</p>

<pre><code>// Process clicks on buttons with class=kb-letter
$(".kb-letter").click(function() {
    var pos = getCaretPos('s');
    // logic for entering Urdu characters in 's' here
});
</code></pre>

<p>This is the function for getting caret position. It returns the current caret position in <code>s</code> and the new character is then inserted at that position:</p>

<pre><code>function getCaretPos(areaId) {
    var txtArea = document.getElementById(areaId);
    var pos = 0;
    var br = (document.selection ? "ie" : ((txtArea.selectionStart || txtArea.selectionStart == '0') ? "ff" : false ) );
    if (br == "ie") { 
        txtArea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtArea.value.length);
        pos = range.text.length;
    }
    else if (br == "ff") {
        pos = txtArea.selectionStart;
    }

    return pos;
}
</code></pre>

<p>Now, the above <code>getCaretPos()</code> works fine in Firefox 8 and Chrome 17 for both direct keyboard input in <code>s</code> and input using clicking on buttons; but on Internet Explorer 8, it works <strong>only</strong> for direct keyboard input. If I try entering a character using mouse clicks, it gets entered at location 0 because <code>getCaretPos()</code> always returns 0 in that case.</p>

<p>I have no idea what is going wrong. Do I need to call <code>getCaretPos()</code> in a different manner in response to mouse clicks for IE?</p>
