Don't fire onfocus when selecting text?

Posted by Casey Hope on Stack Overflow See other posts from Stack Overflow or by Casey Hope
Published on 2010-04-25T01:06:15Z Indexed on 2010/04/25 1:13 UTC
Read the original article Hit count: 412

Filed under:

I'm writing a JavaScript chatting application, but I'm running into a minor problem.

Here is the HTML structure:

<div id="chat">
    <div id="messages"></div>
    <textarea></textarea>
</div>

When the user clicks/focuses on the chat box, I want the textbox to be automatically focused. I have this onfocus handler on the chat box:

chat.onfocus = function () {
    textarea.focus();
}

This works, but the problem is that in Firefox, this makes it impossible to select text in the messages div, since when you try to click on it, the focus shifts to the textarea. How can I avoid this problem?

(Semi-related issues: In Chrome, textarea.focus() doesn't seem to shift the keyboard focus to the textarea; it only highlights the box. IE8 does not seem to respond to the onfocus at all when clicking, even if it tabindex is set. Any idea why?)

© Stack Overflow or respective owner

Related posts about JavaScript