This is a Javascript project, using the jQuery library.
I have a sticky bar I would like to show whenever the browser window is below a certain page position, and otherwise hide it.
Its ID is #sticky-atc-bar
.
The page position is determined by the top of an element with class .product-section
.
Based on research into how to do this, I originally came up with the following JS.
$( document ).ready(function() {
$('#sticky-atc-bar').hide();
var section = $(".product-section");
var offsetSection = section.offset().top; //check for top property
$(function() {
$(window).scroll(function() {
console.log('Scroll Event');
if ($(window).scrollTop() >= offsetSection) { // reached product section
console.log('True:');
$('#sticky-atc-bar').show();
} else { // not reached product section
console.log('False');
$('#sticky-atc-bar').hide();
}
});
});
});
This works. Yet, I am aware it generates a lot of scroll events, the entire time the user is engaged with the page. Knowing that's very inefficient, I went looking for alternative approaches. Along the way I read this article called "Learning from Twitter", which made total sense.
I also came across this solution to a similar requirement. My version of that code is:
var target = $(".product-section").offset().top,
timeout = null;
$('#sticky-atc-bar').hide();
$(window).scroll(function () {
if (!timeout) {
timeout = setTimeout(function () {
console.log('scroll');
clearTimeout(timeout);
timeout = null;
if ($(window).scrollTop() >= target) {
$('#sticky-atc-bar').show();
} else {
$('#sticky-atc-bar').hide();
}
}, 250);
}
});
I set it up on this jsFiddle, and it works.
However ... It still generates a significant number of events. They have simply been reduced to one event every 250 ms, so 4 every second.
What I would like to know is if there's a better way to go about this? Put another way, aside from changing the timeout on this second piece of code, can I reduce this operation to even fewer events? And is that even necessary at this point, or is one event every 250ms not a significant impact?