From 17a0893809f5a8aa9e39336eae9acf4e2dc3afae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonatan=20K=C5=82osko?= Date: Mon, 4 Apr 2022 16:34:01 +0200 Subject: [PATCH] Clear URL hash when the user clicks outside the element (#1089) --- assets/js/hooks/session.js | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/assets/js/hooks/session.js b/assets/js/hooks/session.js index f674c9f05..7b52a4768 100644 --- a/assets/js/hooks/session.js +++ b/assets/js/hooks/session.js @@ -471,6 +471,22 @@ const Session = { if (event.target.closest(`[data-el-enable-insert-mode-button]`)) { this.setInsertMode(true); } + + const hash = window.location.hash; + + if (hash) { + const htmlId = hash.replace(/^#/, ""); + const hashEl = document.getElementById(htmlId); + + // Remove hash from the URL when the user clicks somewhere else on the page + if (!hashEl.contains(event.target) && !event.target.closest(`a`)) { + history.pushState( + null, + document.title, + window.location.pathname + window.location.search + ); + } + } }, /** @@ -575,17 +591,17 @@ const Session = { if (hash) { const htmlId = hash.replace(/^#/, ""); - const element = document.getElementById(htmlId); + const hashEl = document.getElementById(htmlId); - if (element) { - const focusableEl = element.closest("[data-focusable-id]"); + if (hashEl) { + const focusableEl = hashEl.closest("[data-focusable-id]"); if (focusableEl) { this.setFocusedEl(focusableEl.dataset.focusableId); } else { // Explicitly scroll to the target element // after the loading finishes - element.scrollIntoView(); + hashEl.scrollIntoView(); } } } else if (this.props.autofocusCellId) {