0

Could you please check https://jsfiddle.net/s7fxy8jp/8/

Is there any solution to identify tag range so that when I click on "Set Focus To Element Z" from the fiddle, the cursor will appear just after the end of all tag.

HTML

<div tabindex="-1" id="scripted"><a>Element A (script-only focusable)</a><a>Element B (script-only focusable)</a></div><div id="test">Set Focus To Element Z</div>

CSS

div:focus {
background-color: Aqua;}

JS

document.getElementById('test').onclick = function () {
document.getElementById('scripted').focus();};
Soma
  • 31
  • 6

2 Answers2

0

For the cursor to appear, I believe the div must be contentEditable. You could change the attribute onClick to only make it editable after the script activates it.

Once editable you can set the selection to place the cursor position.

function cursorToEnd(el) {
    var range = document.createRange();
    var sel = window.getSelection();
    // Note positioning after the last child works for your
    // example but might not be the most robust option depending
    // on your expected div contents.
    range.setStartAfter(el.lastChild);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}

document.getElementById('test').onclick = function () {
    var e = document.getElementById('scripted');
    e.contentEditable = true;
    cursorToEnd(e);
};

jsFiddle

user650881
  • 2,214
  • 19
  • 31
0

Here is this, but you won't be able to see cursor at the end because i am not converting that div into text box.

document.getElementById('test').onclick = function () {
    document.getElementById('scripted').focus();
   placeCaretAtEnd( document.getElementById("scripted") );
};

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}
div:focus {
  background-color: Aqua;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div tabindex="-1" id="scripted"><a>Element A (script-only focusable)</a><a>Element B (script-only focusable)</a></div>
<div id="test">Set Focus To Element Z</div>
Jigar7521
  • 1,549
  • 14
  • 27