I have a site which uses different page templates and calls jquery to stick the site header on scroll past a certain number of pixels. This sticky class works flawlessly on the page template with a fixed banner, but on the ones where I have not included a banner I would like to change the position at which the scroll function is called. For example, appearing at 250 rather than 500 pixels.
The script is on Wordpress site, built with _s
and sass
and is quoted below:
$(window).scroll(function() {
var sticky = $('.site-header'),
scroll = $(window).scrollTop();
if (scroll >= 500) sticky.addClass('sticky-header');
else sticky.removeClass('sticky-header');
});
The solutions two I can think of are a) Making a conditional statement to trigger different scroll positions based on URL selectors b) Creating a second header div class (.site-header-2
) and an additional jquery document which affects only that class.
The second I can do, although it would be less elegant and time consuming if I were to create multiple page templates all with different fixed scroll heights.
Using the syntax in the script above, is there a simple solution to using a conditional argument, for varying fixed scroll positions based on page URL structure or another way of achieving this which I am unaware of?
Check for existence of your banner element and set scroll start point accordingly
// within document.ready
var isBannerPage = $('#bannerId').length;// adjust selector to fit actual
var scrollStart = isBannerPage ? 500 : 250;
//cache element outside event handler to avoid searching many times a second for same element
var sticky = $('.site-header');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= scrollStart ) sticky.addClass('sticky-header');
else sticky.removeClass('sticky-header');
});