Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/idiomorph.js
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,13 @@ var Idiomorph = (function () {
activeElement?.focus();
}
if (activeElement && !activeElement.selectionEnd && selectionEnd) {
activeElement.setSelectionRange(selectionStart, selectionEnd);
try {
activeElement.setSelectionRange(selectionStart, selectionEnd);
} catch {
// the element may not support setSelectionRange: it's no longer an
// input/textarea after the morph, or it's an input type (number,
// email, date, ...) that doesn't support text selection
}
}

return results;
Expand Down
47 changes: 47 additions & 0 deletions test/restore-focus.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,53 @@ describe("Option to forcibly restore focus after morph", function () {
assertNoFocus();
});

it("does not throw if the saved id resolves to a non-input element after morph", function () {
getWorkArea().innerHTML = `
<div>
<input type="text" id="focused" value="abc">
</div>`;
setFocusAndSelection("focused", "b");

// after the morph nothing input-like has id="focused"; a <div> does
const after = `
<div>
<div id="focused">replaced</div>
</div>`;
(function () {
Idiomorph.morph(getWorkArea(), after, {
morphStyle: "innerHTML",
restoreFocus: true,
});
}).should.not.throw();

getWorkArea().innerHTML.should.equal(after);
assertNoFocus();
});

it("does not throw for input types that reject setSelectionRange", function () {
getWorkArea().innerHTML = `
<div>
<input type="number" id="focused" value="123">
<input type="number" id="other">
</div>`;
// type=number does not support selection, so set focus only
setFocus("focused");

const after = `
<div>
<input type="number" id="other">
<input type="number" id="focused" value="123">
</div>`;
(function () {
Idiomorph.morph(getWorkArea(), after, {
morphStyle: "innerHTML",
restoreFocus: true,
});
}).should.not.throw();

getWorkArea().innerHTML.should.equal(after);
});

it("does not restore selection if selection still set or changed", function () {
getWorkArea().innerHTML = `
<div>
Expand Down
Loading