// Detect request animation frame
const scroll = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.msRequestAnimationFrame
|| window.oRequestAnimationFrame
// IE Fallback, you can even fallback to onscroll
|| function (callback) { window.setTimeout(callback, 1000 / 60); };
let lastPosition = -1;
// my Variables
let lastSection = false;
let replaceItemTop = -1;
let replaceItemBottom = -1;
let replaceItemHeight = -1;
// The Scroll Function
function loop() {
const top = window.pageYOffset;
// my variables
// my sections to calculate stuff
const sections = document.querySelectorAll('.section');
const replaceContainer = document.querySelectorAll('.js-replace');
const replaceItem = document.querySelectorAll('.js-replace__item');
if (replaceItem.length > 0) {
// get top position of item from container, because image might not have loaded
replaceItemTop = parseInt(replaceContainer[0].getBoundingClientRect().top);
replaceItemHeight = replaceItem[0].offsetHeight;
replaceItemBottom = replaceItemTop + replaceItemHeight;
}
let sectionTop = -1;
let sectionBottom = -1;
let currentSection = -1;
// Fire when needed
if (lastPosition == window.pageYOffset) {
scroll(loop);
return false;
}
lastPosition = window.pageYOffset;
// Your Function
Array.prototype.forEach.call(sections, (el, i) => {
sectionTop = parseInt(el.getBoundingClientRect().top);
sectionBottom = parseInt(el.getBoundingClientRect().bottom);
// active section
if ((sectionTop <= replaceItemBottom) && (sectionBottom > replaceItemTop)) {
// check if current section has bg
currentSection = el.classList.contains('section--bg1') || el.classList.contains('section--bg4');
// switch class depending on background image
if (currentSection) {
replaceContainer[0].classList.remove('js-replace--reverse');
} else {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.