Rick Hoving
Rick Hoving

Reputation: 3575

Placing focus on selected text in div FF

I want to automatically select a piece of text so that the user can use ctrl + c to copy it to its clipboard.
In order to do this, I've attached some event handlers to a couple of inputs and a couple of divs (with tabindex="0").
However, if I select a piece of text with javascript, the browser indicates a selection but keeps the focus on the input.
If I try to achieve the same thing but with the div being the trigger, It works.
This behavior is only in FireFox.

In my jsfiddle (or in the snippet below) put the focus on the first input, press a random key (which selects the text), and try to copy paste it in the lower input.
Then try to do the same but with clicking the div. (clicking the div will also select the text).

var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
    selectText(document.getElementById("selectme"));
});

var div = document.getElementById("clickme");
div.addEventListener("click", function(evt){
    selectText(document.getElementById("selectme"));
});

var selectText = function(element){
    var range, selection;
    if(document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if(window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
    element.focus();
}
<input id="my-input"/>
<div id="selectme">Texttexttexttext</div>
<div tabindex="0" id="clickme">CLICK ME</div>
<input />

Upvotes: 0

Views: 118

Answers (1)

Peter Mols
Peter Mols

Reputation: 1031

If you call evt.target.blur(); first, the input will lose its focus before focussing the div.

Your function will look like:

var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
    evt.target.blur();
    selectText(document.getElementById("selectme"));
});

Upvotes: 1

Related Questions