skip to Main Content

I’m building a website in which there are teo ways to scroll

1)scroll snapping

2)traditional

now:

html,body{


 margin: 0;
 
scroll-snap-type:y mandatory ;
flex-direction: column;}

But I want to make button which can turn off scroll sanpping.

I know I can edit css of the body but how to edit the css of the HTML?

2

Answers


  1. Add button with (JavaScript) onclick value:

    document.documentElement.style.scrollSnapType = 'none'
    
    html,body{
    
     margin: 0;
     
    scroll-snap-type:y mandatory ;
    flex-direction: column;}
    
    
    div{
      display: flex;
      height: 400px;
      scroll-snap-align: start;
    }
    button{
      position: fixed;
    }
    <button onclick="document.documentElement.style.scrollSnapType = 'none';">disable scroll-snap-type</button>
    <div style="background:#844"></div>
    <div style="background:#484"></div>
    <div style="background:#448"></div>
    Login or Signup to reply.
  2. Create a button in your HTML to toggle scroll snapping:

    <button id="toggleScrollSnapping">Toggle Scroll Snapping</button>
    

    Add an event listener to the button to toggle the scroll snapping behavior:

    const toggleButton = document.getElementById('toggleScrollSnapping');
    const htmlElement = document.documentElement;
    
    toggleButton.addEventListener('click', () => {
        htmlElement.classList.toggle('scroll-snapping-disabled');
    });
    

    Define your CSS rules to enable or disable scroll snapping based on the class applied to the element:

    html {
        /* ... other CSS rules ... */
    }
    
    body {
        margin: 0;
        flex-direction: column;
    }
    
    .scroll-snapping-enabled {
        scroll-snap-type: y mandatory;
    }
    
    .scroll-snapping-disabled {
        scroll-snap-type: none;
    }
    

    Apply the CSS class to the element when the button is clicked:

    toggleButton.addEventListener('click', () => {
        htmlElement.classList.toggle('scroll-snapping-disabled');
        htmlElement.classList.toggle('scroll-snapping-enabled');
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search