Start animation at beginning of new section

I have the following js function to toggle the navabar from beeing transparant to a solid background:

	$(window).scroll(function(){
		$('nav').toggleClass('scrolled', $(this).scrollTop() > 200)
	});

As you can see is the transition triggerd when scrolled to 200px. What I am looking for is a way to make the transition happen when the second div (.intro) has reached the top of the viewport

Hi @donboe, you can check if the window scroll top is greater than the intro element’s offset top like so:

var $window = $(window)
var $nav = $('nav')
var introTop = $('.intro').offset().top

$window.scroll(function () {
  var scrollTop = $window.scrollTop()
  $nav.toggleClass('scrolled', scrollTop > introTop)
})

Note that scroll event listeners can generally be pretty expensive, so it’s advisable to perform only the necessary computations in the handler function and whatever possible outside of it (such as querying the DOM for the nav element). You might also consider throttling the event handler invocation.

1 Like

Hi. @m3g4p0p. Thank you very much. Very nice as ever. Working very nice. I’m going to read the article about throttling later on this evening. Very interessting indeed.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.