Skip to content

Commit

Permalink
Scroll offset fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhibbitts committed Oct 15, 2024
1 parent 7135337 commit df4d30c
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,50 @@

});

hook.ready(function () {
// Original code by @rizdaprasetya and further improved with the assistance of ChatGPT, an AI language model by OpenAI
let TARGET_QUERY = 'id';
let SCROLL_DELAY = 650; // in milliseconds
let location = window.location;

// Build the current URL without the hash
let currentUrlWithoutHash = new URL(
location.origin + location.pathname +
location.search
);

// Get the search parameters from the URL (before the hash)
let urlQueryParam = currentUrlWithoutHash.searchParams;
let isUrlHasIdQuery = urlQueryParam.has(TARGET_QUERY);

// Handle the case where the 'id' is in the fragment (hash) part
let hashParams = new URLSearchParams(location.hash.split('?')[1]); // Get the query params after `#`
let isHashHasIdQuery = hashParams.has(TARGET_QUERY);

// Check if the URL contains the 'id' query parameter in either search or hash
if (isUrlHasIdQuery || isHashHasIdQuery) {

// Get the 'id' from either search or hash
let urlId = isUrlHasIdQuery ? urlQueryParam.get(TARGET_QUERY) : hashParams.get(TARGET_QUERY);

// Delay the scrolling to ensure everything is loaded
setTimeout(function () {
try {
let targetElement = document.querySelector('#' + urlId);
if (targetElement) {
// Scroll to the element with smooth behavior
targetElement.scrollIntoView({
behavior: 'smooth', // Enables smooth scrolling
block: 'start', // Aligns the top of the element to the top of the viewport
});
}
} catch (e) {
console.log('custom scroll failed', e);
}
}, SCROLL_DELAY);
}
});

}
]
}
Expand Down

0 comments on commit df4d30c

Please sign in to comment.