Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set width of scrollbar in JS to 8px

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`;
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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`;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading