There are a couple of different ways to approach this issue. One method is to manually trigger the scroll event either on page load or when the DOM is ready. Another option is to consolidate all of the logic into a function that can be called by the scroll event as well as during page load or when the DOM is ready.
Solution 1: Utilize a custom function for scrolling and page events
$(function() {
// Create custom function to handle all necessary logic
var customScrollCallback = function() {
var top = $(window).scrollTop();
if (top >= 1) {
$("header").addClass('bg-header');
} else if ($("header").hasClass('bg-header')) {
$
};
};
$(window).scroll(function() {
// Call custom function on scroll
customScrollCallback();
});
// Execute custom function at runtime :) (a handy trick!)
customScrollCallback();
});
Solution 2: Manually trigger the scroll
event (not recommended)
This second solution may not be ideal because there could be other plugins or scripts on the page that rely on the scroll
event. When you manually trigger this event, it disrupts the expected behavior of the event (as it fires without any actual scrolling occurring).
$(function() {
$(window)
.scroll(function() {
var top = $(window).scrollTop();
if (top >= 1) {
$("header").addClass('bg-header');
} else if ($("header").hasClass('bg-header')) {
$("header").removeClass('bg-header');
}
})
.trigger('scroll');
});