Home > Enterprise >  Set width of scrollbar in JS to 8px
Set width of scrollbar in JS to 8px

Time:12-22

I need to amend the following code that is detecting the scrollbar width. It is opening a fullscreen menu by applying "overflow-y:hidden" to "html" when the menu is opened. This code should add a fake scrollbar to stop the content jumping to the right. Im also using a custom scrollbar that is 8px wide, so I think I just need to amend the code below to make the fake scrollbar 8px.

menuButton.addEventListener('click', () => {

   // get width before hiding scrollbar
   let oldWidth = document.documentElement.clientWidth;

   // toggle CSS class that sets overflow to hidden
   document.querySelector("html").classList.toggle("no-scroll");

   // get new width after hiding scrollbar
   let newWidth = document.documentElement.clientWidth;

   // set margin-right value equal to width of the scrollbar
   let scrollbarWidth = Math.max(0, newWidth - oldWidth);
   document.body.style.marginRight = `${scrollbarWidth}px`;
});

CodePudding user response:

To make the fake scrollbar 8px wide, you can simply update the value of the scrollbarWidth variable to 8.

Here's the updated code:

menuButton.addEventListener('click', () => {

// get width before hiding scrollbar let oldWidth = document.documentElement.clientWidth;

// toggle CSS class that sets overflow to hidden document.querySelector("html").classList.toggle("no-scroll");

// get new width after hiding scrollbar let newWidth = document.documentElement.clientWidth;

// set margin-right value equal to width of the scrollbar let scrollbarWidth = 8; document.body.style.marginRight = ${scrollbarWidth}px; });

  • Related