Intersection Observer API, counter and scope of a variable + Developing a slider

I don’t think that’s working very well as there’s some fuzzy logic in there and the divs are flying backwards and forwards due to the method you are using to slide them.

It would be easier if you had an extra wrapper or two and then you could slide the wrapper by 100% which would slide all the divs that were visible each time rather than trying to slide a number of individual divs.

Also I think you only need to know how many items are in the viewport at any given time and then you can work out how many times you can slide them. For example if you had 3 items in the viewport and you have 12 elements then you only need to slide 4 times. If you keep a counter and then check this each time you slide (in case the screen was resized and less/more were in the viewport) then you could act accordingly.

Here’s a rough demo of what I mean but instead of using the Intersection Observer to find how many items are visible I simply grab the css custom variable that dictates how many are visible. After all it’s the css that dictates how many are visible anyway.

This is only a quick and dirty demo but of you resize the screen it goes from 4 across to one across but still slides a screenful at a time whatever. Instead of using the css variable to get the ratio I’m sure you could use the instersection observer to get the same ratio although it would be more code.

I’m not sure if that helps much as I got lost in the logic of your actual code although I notice that there is an error in the console at certain points.

1 Like