Dany Dany - 1 year ago 62
jQuery Question

Focus an input field when clicking on an element, except if some text within the container was highlighted

An input field

needs to be be focused when clicking on a container element
EXCEPT if text inside that element was (highlighted via either double click or mouse selection)

// what I got so far which is incomplete
$('#text').on('click', function (e) {

Fiddle: https://jsfiddle.net/xhykmtwy/4/

Answer Source

You may want to consider the solution below, which checks if some text is selected in the text element after the click event:

$('#text').click(function () {
    var container = this;
    setTimeout(function () {
        var selectedElement = null;
        var selectedText = null;
        if (window.getSelection) {
            // For modern browsers
            var selection = window.getSelection();
            if (selection) {
                selectedText = selection.toString();
                if (selection.anchorNode) {
                    selectedElement = selection.anchorNode.parentNode;
        else if (document.selection && document.selection.type === "Text") {
            // For IE < 9
            var selection = document.selection;
            selectedText = selection.createRange().text;
        if (!(selectedText && selectedText.length > 0) || (selectedElement !== container && !$(container).has(selectedElement))) {
            setTimeout(function () { $('#chatInput').focus(); }, 0);
    }, 0);

According to my tests, it works in IE (including IE7), Firefox and Chrome. The only exception is the double-click in IE, which does not select the text. You can see the result in this jsfiddle.

The calls to setTimeout ensures that all the selection processing has been done, especially when clicking on the selected text to deselect it.


  1. I used the method proposed by Eineki in How can I get the element in which highlighted text is in? to check if the text element contains the selected text.

  2. The code for processing the selection in IE < 9 was found in Tim Down's answer to the post Get the Highlighted/Selected text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download