Reputation: 51
I want to add/remove a class based on scroll position AND window width. The class should be added when the user scrolls vertically past X AND the window width is larger than Y. If BOTH conditions are not met, the class should be removed. If the user scrolls back to the top, the class should be removed as well.
Both the scroll position and window width values must be dynamic, so the values are measured continuously.
Basically, I need to combine the following functions that each work on their own.
Thanks in advance for any help!
The scroll function that works:
jQuery(function($){
var shrinkHeader = 200; //
// Add dynamic header class
$(window).scroll(function () {
var scroll = getCurrentScroll();
if ( scroll >= shrinkHeader) {
$('.site-header').addClass('shrink');
}
else {
$('.site-header').removeClass('shrink');
}
});
The width function that works:
jQuery(function($){
var shrinkHeader = 200;
var $window = $(window);
function checkWidth() {
var windowsize = $window.width();
if (windowsize >= 1151) {
$('.site-header').addClass('shrink');
}
else {
$('.site-header').removeClass('shrink');
}
}
checkWidth(); // Check window width on load
$(window).resize(checkWidth); // Check window width on resize
Upvotes: 0
Views: 2600
Reputation: 51
I actually solved the issue as follows below. This allows the scroll AND window values to be returned continuously. Would love to hear any thoughts if there is a more efficient strategy.
jQuery(function($){
var shrinkHeader = 200; // Scroll value
// Add/Remove dynamic header class .shrink on scroll
$(window).scroll(function () {
var scroll = getCurrentScroll();
var windowWidth = getCurrentWidth();
if (scroll >= shrinkHeader && windowWidth >= 1151) {
$('.site-header').addClass('shrink');
}
else {
$('.site-header').removeClass('shrink');
}
});
// Add/Remove dynamic header class .shrink per window width
$(window).resize(function () {
var windowWidth = getCurrentWidth();
var scroll = getCurrentScroll();
if (windowWidth >= 1151 && scroll >= shrinkHeader) {
$('.site-header').addClass('shrink');
}
else {
$('.site-header').removeClass('shrink');
}
});
// Check current scroll position
function getCurrentScroll() {
return window.pageYOffset || document.documentElement.scrollTop;
}
// Check window width on load
getCurrentWidth();
// Return window width
function getCurrentWidth() {
return $(window).width();
}
});
Upvotes: 1
Reputation: 195
Its just simple. Put widow width condition inside window scroll function. I am using this for widow scroll lazy loading. But i did it for height! Hope it helps
$(window).scroll(function () {
var windowsize = $window.width();
if (windowsize >= 1151) {
$('.site-header').addClass('shrink');
}
else {
$('.site-header').removeClass('shrink');
}
});
Upvotes: 1