Skip to content

Instantly share code, notes, and snippets.

@neilellis
Last active December 15, 2015 00:38
Show Gist options
  • Save neilellis/5174183 to your computer and use it in GitHub Desktop.
Save neilellis/5174183 to your computer and use it in GitHub Desktop.
Simple GWT 'sticky' scroll handler - like the one used in http://boardcast.it - it will cause scrolling to 'stick' from headerTopTriggerInPixels to headerBottomTriggerInPixels with a gravity towards initialScrollPosition. Useful if you have content you wish to 'hide' above the normal viewable area.
import com.google.gwt.user.client.Window;
public class StickyTopScrollHandler implements Window.ScrollHandler {
private final int headerTopTriggerInPixels;
private final int headerBottomTriggerInPixels;
private final int initialScrollPosition;
private Timer timer;
private int oldTop;
public StickyTopScrollHandler(int headerTopTriggerInPixels, int headerBottomTriggerInPixels, int initialScrollPosition) {
this.headerTopTriggerInPixels = headerTopTriggerInPixels;
this.headerBottomTriggerInPixels = headerBottomTriggerInPixels;
this.initialScrollPosition = initialScrollPosition;
}
@Override public void onWindowScroll(Window.ScrollEvent event) {
if (Window.getScrollTop() > headerTopTriggerInPixels
&& Window.getScrollTop() < headerBottomTriggerInPixels
&& timer == null) {
oldTop = Window.getScrollTop();
timer = new Timer() {
int count = headerBottomTriggerInPixels - headerTopTriggerInPixels;
@Override public void run() {
count--;
if (Window.getScrollTop() == initialScrollPosition
|| count == 0
|| Window.getScrollTop() < headerTopTriggerInPixels
|| Window.getScrollTop() > headerBottomTriggerInPixels) {
timer.cancel();
timer = null;
}
final int delta = (int) Math.signum(initialScrollPosition - Window.getScrollTop());
if (oldTop == Window.getScrollTop() || ((int) Math.signum(Window.getScrollTop() - oldTop)) != delta) {
Window.scrollTo(Window.getScrollLeft(), Window.getScrollTop() + delta);
}
}
};
timer.scheduleRepeating(10);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment