Don't run onfocus on text selection?

I am writing a JavaScript chat application but I have a problem.

Here is the HTML structure:

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

      

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

in a chat window:

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

      

This works, but the problem is that in Firefox it makes it impossible to select text in messages div

, because when you try to click on it, the focus goes to textarea

. How can I avoid this problem?

(Semi-related issues: In Chrome textarea.focus()

, it doesn't seem to switch keyboard focus to textarea

, it only selects the margin. IE8 doesn't seem to respond at all onfocus

when clicked, even though it's set tabindex

. Any idea why?)

+2


a source to share


4 answers


I found a solution to automatically select the textbox when clicking on the chat, keeping the option to select the text: just change div

to label

.

<label id="chat" style="display: block">
    <div id="messages"></div>
    <textarea></textarea>
</label>

      



Unfortunately Firefox has a bug where it overrides and forces it to label

be inline, but this can be fixed by dynamically building it with JavaScript.

0


a source


What if you used the on mouse up event. Then check if the user has anything selected if it doesn't give focus to the textarea. it makes sense?



about cross-browser issues you might view in jQuery or another javascript library. You don't need all of this unless you intend to use it, but you can grab parts to make the focus work in all browsers.

+1


a source


you can try setTimeout to focus the text area, something like this:

setTimeout(function() {
    textarea.focus();
}, 1000);

      

0


a source


The onfocus event only exists for form elements: LABEL, INPUT, SELECT, TEXTAREA, and BUTTON. Using onclick event for chat.

0


a source







All Articles