I have 3 variables top, mid, bot
that I want to be logged depending on which part the div
pops up (if topmost part of div
, then top
would be logged)
All you need to know is as the user scrolls down from the top of page, there are certain divs
that we want to target. The 3 variables represent what needs to be logged whenever we hit a certain part of the div.
How would rewrite the console.log
ternary operator to make sense, right now, the mid is not being run at all.
EDIT
trgt1 and trgt2
are 2 divs with the class ( .column
). trgt1
is the very first div that shows up, trgt2
should pop up as we scroll through halfway through the div.
CODE
function onScroll(event){
let top = "Column with id:`id-10` started to become visible on the page."
let mid = "Column with id:`id-50` is now more than 50% visible on the page."
let bot = "Column with id:`id-40` is now fully visible on the page."
targets.forEach(
function(trgt,index){
let isVisible = isScrolledIntoView(trgt);
if (visibleStates[index] != isVisible)
console.log(`Element index ${index} is now ${isVisible === trgt1 ? top : (isVisible === trgt2 ? mid : bot)}`);
visibleStates[index] = isVisible;
}
);
}
You could work with a script that runs on scrolling the page. So add an eventlistener to the page.. Then you can debounce the scrolling, so control the amount of noise you allow on the window.. The function I have included is a working debounce function, just play with the wait in milliseconds. And then use your debounce function on the checkSlide() function where you put your running code in.
I know this is not a direct answer, it is another way of approaching the problem. This could work. If you want to do it your way, go for it..
Good luck!
window.addEventListener('scroll', debounce(checkSlide));
function checkSlide(){}
function debounce(func, wait=20, immediate = true){
var timeout;
//debounce is a higher order function and will return another function
return function run_code() {
var context = this;
//arguments is local variable of a function, refers to all arguments
var args = arguments;
//variable later is a function
var later = function(){
timeout = null;
//if it is not time zero, apply checkSlide function
if(!immediate) func.apply(context, args);
};
var Callnow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(Callnow) func.apply(context, args);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.