How to set and call ScrollLeft() position

I'd like to set the scrollLeft() position and call it back. Here's my codepen...

When you click "Zoom out" you can scroll left to right. When you click on a box, it focuses on that box. Then, when you click "Zoom out", the scroll goes back to 0. However, I'd like the scroll to be where it was when you initially click on a box. Right now, if you click on say, the last box, then zoom out again, the scrollLeft position goes back to 0. I know I can set a variable...

var scrollPosition = $('body').scrollLeft();

But I'm not sure where to go from there. Even when I set this variable, the console says it can't read it. I'm novice in JS, but I'd really like to figure this out. If you have a better solution or a way to solve this with scrollLeft() or another method, please help. Thanks.

Answers 1

  • Add var scrollX = 0; as a global variable in your JS file.

    Then add scrollX = document.body.scrollLeft; at the top of your $('.box').click(function() { function.

    Last, add document.body.scrollLeft = scrollX; at the end of your function zoomOut() { function.

    Here is a working codepen:

Related Articles