Home > Back-end >  How can I code a css scroll-snap-stop always in pure javascript?
How can I code a css scroll-snap-stop always in pure javascript?

Time:09-20

That's pretty much the question. I have search everywhere online, but I cannot find any implementation of the css scroll-snap-stop: always written in pure javascript.

I do not want to use the css property because not all browsers respect it (let alone older browsers).

Does any one have any sample code around that does something similar? I do not know where to look or how to start.

Here is an example of I working here https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-stop

It forces the user to stop at each section

[EDIT] -- I basically want the same functionality of what scroll-snap-stop: always does without using it. There should be no css, just pure javascript that mimics that same css behavior.

I need pure javascript instead of css because not all browsers honour the scroll-snap-stop: always css property. So I wanted to code a javascript alternative that does the same thing.

CodePudding user response:

  • Do the mode switch in JS, or even a pure HTML button.
  • Do the style in CSS.

Use JavaScript to change the class of the element. And use CSS to style the two classes.

This method is style independent.

CodePudding user response:

Say you have a list of items that overflow (with ul being its overflowing container):

  • ul
    • li
    • li
    • li

When the page loads, you set all list items to display none, except for the first two. You set the second one to 1px width and set the first one to its normal width. When the second one enters the viewport (intersection observer) you expand the second one to its normal width. You then also set the third one to 1px width and set it to display block. When the first one leaves the viewport (intersection observer) you set the width of that one to 1px... etc. This should mimic the CSS rule.

You could code this... and it would perform absolutely great... but I would not do it. Browser compatibility of 'scroll-snap-stop: always' is fine: https://caniuse.com/?search=scroll snap

  • Related