Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplebar scrollbar plugin - Scroll to top / reset position in function

I need to be able to scroll back to the top of a page within my ui-routed angular one-page site when a function is triggered, but I've used the simplebar scrollbar plugin as a custom scroller, so can't use the window scrolltop method to take the user back to the top of the page.

I can't use any window/document scrolling method as the container that utilises simplebar is a fixed 100vh container, therefore the window is always scrolled to the top.

I've tried using the jquery method below to reset the position of the scrollbar back to the top, but can't get it working, and there are no error messages in the console.

angular.element('#mainContent').simplebar('getScrollElement').scrollTop(0);

I've also tried this in plain js, which returns 'is not a function' in the console:

var mainContent = new SimpleBar(document.getElementById('mainContent'));

mainContent.SimpleBar.getScrollElement().scrollTop = 0;


2 Answers

It seems that the new SimpleBar(xxx) approach does not work with data-simplebar html attribute. I don't want to initialize the SimpleBar programmatically so I used this in stead:

$('#mainContent .simplebar-content-wrapper').scrollTop(some_value)

The actual scrollable element would have simplebar-content-wrapper class, and it would be inside the element that you've added SimpleBar for.

The class simplebar-content-wrapper was mentioned in its documentation and can be expected to be consistent across versions.

There would be problem if you have cascaded SimpleBars. Solutions:

  1. $('#mainContent .simplebar-content-wrapper')[0].scrollTop = some_value: This would only scroll the correct SimpleBar because the elements returned by nowaday JQuery is in document order.
  2. $('#mainContent>>>>.simplebar-content-wrapper').scrollTop(some_value): The hierarchy of SimpleBar components is not guaranteed to be unchanged in future versions and this may fail in the future.
like image 108
Meow Cat 2012 Avatar answered Oct 18 '25 06:10

Meow Cat 2012


I have found the solution. You can access scroll element:

const el = new SimpleBar(document.getElementById('layout'));
el.scrollContentEl.scrollTop = 0;
like image 22
Alex Avatar answered Oct 18 '25 05:10

Alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!