Skip to content

Commit

Permalink
Fix a problem in scrolling with anchor link
Browse files Browse the repository at this point in the history
- this solved the problem docsifyjs/docsify#351 (comment)
  • Loading branch information
ksugar committed Mar 29, 2022
1 parent 93c6f37 commit a286257
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
40 changes: 40 additions & 0 deletions docs/assets/js/docsify-fix-pageload-scroll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// https://github.com/rizdaprasetya/docsify-fix-pageload-scroll (MIT License)
; (function (win) {
function create(param) {
var isParamExist = (typeof param === 'object');

return function (hook, vm) {
hook.ready(function () {
// true = show debug log
var dd = isParamExist && param.isDebug || false;
var TARGET_QUERY = isParamExist && param.targetParam || 'id';
var SCROLL_DELAY = isParamExist && param.scrollDelay || 1000; // in milisecond
var location = window.location;

dd && console.log('custom scroll plugin called');
var currentUrlWithoutHash = new URL(
location.origin + location.pathname +
location.search + location.hash.substring(1)
)
var urlQueryParam = currentUrlWithoutHash.searchParams;
var isUrlHasIdQuery = urlQueryParam.has(TARGET_QUERY);
if (isUrlHasIdQuery) {
dd && console.log('url has id, will scroll to element');
var urlId = urlQueryParam.get(TARGET_QUERY);
// run delayed, to make sure everything loaded
setTimeout(function () {
dd && console.log('will scroll now!');
try {
document.querySelector('#' + urlId).scrollIntoView();
} catch (e) { dd && console.log('custom scroll failed', e) }
}, SCROLL_DELAY);
}
})
}
}
win.DocsifyPageloadScrollPlugin = {};
win.DocsifyPageloadScrollPlugin.create = create;
if (typeof win.$docsify === 'object') {
win.$docsify.plugins = [].concat(create(), $docsify.plugins);
}
})(window);
2 changes: 2 additions & 0 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@
<script src="//unpkg.com/docsify/lib/plugins/zoom-image.min.js"></script>
<!-- https://github.com/alertbox/docsify-footer (MIT License) -->
<script src="//cdn.jsdelivr.net/npm/@alertbox/docsify-footer/dist/docsify-footer.min.js"></script>
<!-- https://github.com/rizdaprasetya/docsify-fix-pageload-scroll (MIT License) -->
<script src="../assets/js/docsify-fix-pageload-scroll.js"></script>
<script>
function setImageVisible(event, id) {
var img = document.getElementById(id);
Expand Down

0 comments on commit a286257

Please sign in to comment.