diff --git a/js/src/util/scrollbar.js b/js/src/util/scrollbar.js index b78b5888b250..8a5594dcbe42 100644 --- a/js/src/util/scrollbar.js +++ b/js/src/util/scrollbar.js @@ -13,7 +13,7 @@ const SELECTOR_STICKY_CONTENT = '.sticky-top' const getWidth = () => { // https://muffinman.io/blog/get-scrollbar-width-in-javascript/ - const documentWidth = document.documentElement.clientWidth + const documentWidth = Math.max(document.documentElement.clientWidth, document.body.clientWidth) // const documentWidth = document.body.getBoundingClientRect().width return Math.abs(window.innerWidth - documentWidth) } @@ -26,8 +26,13 @@ const hide = (width = getWidth()) => { } const _setElementAttributes = (selector, styleProp, callback) => { + const scrollbarWidth = getWidth() SelectorEngine.find(selector) .forEach(element => { + if (element !== document.body && window.innerWidth > element.clientWidth + scrollbarWidth) { + return + } + const actualValue = element.style[styleProp] const calculatedValue = window.getComputedStyle(element)[styleProp] Manipulator.setDataAttribute(element, styleProp, actualValue) diff --git a/js/tests/unit/util/scrollbar.spec.js b/js/tests/unit/util/scrollbar.spec.js index cbbec57cf635..0147942d5fc9 100644 --- a/js/tests/unit/util/scrollbar.spec.js +++ b/js/tests/unit/util/scrollbar.spec.js @@ -111,5 +111,25 @@ describe('ScrollBar', () => { expect(currentMargin).toEqual(originalMargin, 'sticky element margin should be reset after closing') done() }) + + it('should not adjust the inline margin and padding of sticky and fixed elements when element do not have full width', () => { + fixtureEl.innerHTML = [ + '
' + ].join('') + + const stickyTopEl = fixtureEl.querySelector('.sticky-top') + const originalMargin = Number.parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10) + const originalPadding = Number.parseInt(window.getComputedStyle(stickyTopEl).paddingRight, 10) + + Scrollbar.hide() + + const currentMargin = Number.parseInt(window.getComputedStyle(stickyTopEl).marginRight, 10) + const currentPadding = Number.parseInt(window.getComputedStyle(stickyTopEl).paddingRight, 10) + + expect(currentMargin).toEqual(originalMargin, 'sticky element\'s margin should not be adjusted while opening') + expect(currentPadding).toEqual(originalPadding, 'sticky element\'s padding should not be adjusted while opening') + + Scrollbar.reset() + }) }) })