How to make the viewport scroll to follow an element

I have some objects that when clicked will be dragged to the top of the scene.
Is there a way to make the viewport scroll up to follow them?

Test1.hype.zip (1.3 MB)

The only way to really do this is with a bit of code.

There's three basic steps:

  1. In the Identity Inspector, add a Unique Element ID to the element you want to follow so that we can get at it with code
  2. Add another action to the On Mouse Click event to Run JavaScript…
  3. Add code that constantly checks the top position of the element and uses the window.scrollTo() method to change the scroll location. It can stop when the animating timeline is completed.

The code would look something like:

	// define a function that will scroll based on the position of the 'Etiqueta6' element (Unique Element ID definied in Hype's Identity Inspector)
	var updateScroll = (function () {
		// get the element
		var etiqueta6Element = hypeDocument.getElementById('Etiqueta6');
		
		// get the top position
		var scrollTop = etiqueta6Element.getBoundingClientRect().top;
		
		// have a 20px margin on top so there's some spacing
		scrollTop = Math.max(0, scrollTop - 20); 
		
		// perform the scroll
		window.scrollTo({top: scrollTop, behavior: 'smooth'});
		
		// call this method again if we're not done with the Braco timeline
		var currentTime = hypeDocument.currentTimeInTimelineNamed('Braco');
		var duration = hypeDocument.durationForTimelineNamed('Braco')
		if(currentTime < duration) {
			window.requestAnimationFrame(updateScroll);
		}
	});
	
	// always invoke once to kick it off
	updateScroll();

Here's the basic document with these changes:
Test1-fixed.hype.zip (1.3 MB)

It seems to work pretty well on Safari and Firefox, but lags a bit in Chrome. I'm not sure why... I thought if I change the scroll behavior to 'instant' that might help, but it results in weird artifacting. There might be some other smooth scrolling libraries that could help more with this that don't encounter the issue; I'm not really sure.

2 Likes