diff --git a/js/anchor-scroll.js b/js/anchor-scroll.js index 6efad0b..3bf14d8 100644 --- a/js/anchor-scroll.js +++ b/js/anchor-scroll.js @@ -18,14 +18,14 @@ * Returns true if target element for scrolling is found, false other way. */ function scrollToId(id) { - var element = document.getElementById(id); - if (element) { + var targetElement = document.getElementById(id); + if (targetElement) { var options = drupalSettings.bs_lib.anchor_scroll; // Used to trigger sticky header with small amount of scroll to trigger // sticky header so calculation is more accurate. // @fixme - this is a hack, if possible fix it or remove it for now! - window.scrollTo({top: 50}); + //window.scrollTo({top: 50}); // Find fixed element with a biggest offset from viewport top and use // that one to calculate element scroll value. @@ -39,20 +39,22 @@ biggestOffset = biggestOffset < fixedElementOffset ? fixedElementOffset : biggestOffset; } + // Focus the target element, important for accessibility. + targetElement.focus(); + if (document.activeElement !== targetElement) { + // If element is not focusable set tabindex first. + targetElement.setAttribute('tabindex','-1'); + targetElement.focus(); + } + // Scroll to element. + // This needs to happen after focusing because focus will also trigger + // scrolling. window.scrollTo({ - top: window.scrollY + element.getBoundingClientRect().top - (options.offset + biggestOffset), + top: window.scrollY + targetElement.getBoundingClientRect().top - (options.offset + biggestOffset), behavior: 'smooth' }); - // Focus the target element, important for accessibility. - target.focus(); - if (document.activeElement !== element) { - // If element is not focusable set tabindex first. - element.setAttribute('tabindex','-1'); - element.focus(); - } - return true; } @@ -94,3 +96,4 @@ } }(jQuery, drupalSettings)); +