Skip to content

Commit

Permalink
Save and restore focus after DOM manip
Browse files Browse the repository at this point in the history
  • Loading branch information
1Marc committed Mar 12, 2024
1 parent d92ce3f commit b87b80e
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions js/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,28 @@ const App = {
li.querySelector('[data-todo="edit"]').value = todo.title;
return li;
},
saveFocus() {
const $active = document.activeElement;
const $parent = $active && $active.closest("[data-id]");

App.focusedSelector = $parent
? `[data-id="${$parent.dataset.id}"] ${$active.tagName.toLowerCase()}`
: null;
},
restoreFocus() {
if (!App.focusedSelector) return;

const $el = App.$.list.querySelector(App.focusedSelector);
if ($el) {
$el.focus();
}
},
render() {
const count = Todos.all().length;
App.$.setActiveFilter(App.filter);
App.saveFocus();
App.$.list.replaceChildren(...Todos.all(App.filter).map((todo) => App.createTodoItem(todo)));
App.restoreFocus();
App.$.showMain(count);
App.$.showFooter(count);
App.$.showClear(Todos.hasCompleted());
Expand All @@ -122,3 +140,4 @@ const App = {
};

App.init();
window.App = App;

0 comments on commit b87b80e

Please sign in to comment.