Don't fire onfocus when selecting text?
I'm writing a JavaScript chatting application, but I'm runn开发者_C百科ing 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?)
What if you used the on mouse up event instead. Then check if the user has anything selected, if not give textarea focus. does that make sense?
about the cross-browser issues you could look into jQuery or another javascript library. You don't need the whole thing if your not going to use it but you could grab the parts to make focus work in all browsers.
you might want to try setTimeout to focus the text area, something like this :
setTimeout(function() {
textarea.focus();
}, 1000);
Event onfocus exist only for form elements: LABEL, INPUT, SELECT, TEXTAREA and BUTTON. Using onclick event for chatbox.
I've found a solution to automatically select a textarea when clicking on the chat while still being able to select text: simply change div
into label
.
<label id="chat" style="display: block">
<div id="messages"></div>
<textarea></textarea>
</label>
Unfortunately, Firefox has a bug where it overcorrects and forces label
to be inline, but this can be fixed by dynamically creating it using JavaScript.
精彩评论