Title

jQuery action on scroll Y position or element trigger

description

Use jQuery actions on scroll, for example to show a header only on scrolling up, or changing section color when scrolling past a specific element.

Published 2022-08-26

Modified 2022-09-29

content

Y position trigger

				
					jQuery(function($){
	var screen = $(window);
	var screenPosition = screen.scrollTop();
	var header = $('header');

	// Scroll down and collaps header up, scroll up and return header down
	function header_up_down() {
		if (screenPosition > 40) {
		if(screen.scrollTop() > screenPosition) {
			header.addClass('headerup');
		} else {
			header.removeClass('headerup');
		}
		}
		screenPosition = screen.scrollTop();
	}
	//fire the above function
	screen.on('scroll resize', header_up_down);
});
				
			
				
					header{
-webkit-transition: transform 0.34s ease;
transition : transform 0.34s ease;
}
header.headerup{
transform: translateY(-80px); /*adjust this value to the height of your header*/
}
				
			

Scroll past element trigger

				
					//get offsets for your trigger div's.  Default 0, change using $('#trigger').offset({top:100})
//each object is by using trigger1.top, trigger2.top, or whatever you name your variables
jQuery(document).ready(function($){
	$('#websites article:last-of-type section.elementor-top-section').attr('id','trigger3');
	var trigger1 = $('#trigger1').offset();
	var trigger2 = $('#trigger2').offset();
	var trigger3 = $('#trigger3').offset();
	var trigger4 = $('#trigger4').offset();
	
	function trigger_position_actions() {
  		var screenPosition = $(document).scrollTop();
        if (screenPosition < trigger1.top) {
            $('body').addClass('pinkbg');
            $('body').removeClass('whitebg bgflasher greybg');
        }
        if (screenPosition >= trigger1.top) {
            $('body').addClass('whitebg');
            $('body').removeClass('pinkbg bgflasher greybg');
        }
	    if (screenPosition >= trigger2.top) {
            $('body').addClass('greybg');
            $('body').removeClass('whitebg bgflasher pinkbg');
        }
	    if (screenPosition >= trigger3.top) {
            $('body').addClass('pinkbg');
            $('body').removeClass('whitebg bgflasher greybg');
        }
	  	if (screenPosition >= trigger4.top) {
            $('body').addClass('whitebg bgflasher');
            $('body').removeClass('pinkbg greybg');
        }
	}
	$(window).on('scroll resize', trigger_position_actions);
	$(document).ready(trigger_position_actions);
});