What I am aiming to achieve is something that looks like this. you can see it in action on this URL, if you scroll a bit.
I was thinking at first to try using inViewport, and every time a heading or a paragraph is in viewport to show one image and hide the previous. but my problem is that the elements are in viewport in conjunction
This is the initial code I was using:
$.fn.isInViewport = function () {
let elementTop = $(this).offset().top;
let elementBottom = elementTop + $(this).outerHeight();
let viewportTop = $(window).scrollTop();
let viewportBottom = viewportTop + window.innerHeight; // <-- here
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).scroll(function () {
if ($('.heading1 ').isInViewport()) {
// Use .blogcard instead of this
$('.img1').addClass('show');
} else {
// Remove class
$('.img1').removeClass('show');
}
if ($('.heading2 ').isInViewport()) {
// Use .blogcard instead of this
$('.img2').addClass('show');
} else {
// Remove class
$('.img2').removeClass('show');
}
});
I have found this answer but have no idea on how can I use is to my benefits.
I have also stumbled upon this solution, which looks even smarter, but the code adds the classes to the selector in viewport and not to a different element.
This is the code applied there:
ar getElementsInArea = (function(docElm){
var viewportHeight = docElm.clientHeight;
return function(e, opts){
var found = [], i;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
for( i = opts.elements.length; i--; ){
var elm = opts.elements[i],
pos = elm.getBoundingClientRect(),
topPerc = pos.top / viewportHeight * 100,
bottomPerc = pos.bottom / viewportHeight * 100,
middle = (topPerc + bottomPerc)/2,
inViewport = middle > opts.zone[1] &&
middle < (100-opts.zone[1]);
elm.classList.toggle(opts.markedClass, inViewport);
if( inViewport )
found.push(elm);
}
};
})(document.documentElement);
////////////////////////////////////
// How to use:
window.addEventListener('scroll', f)
window.addEventListener('resize', f)
function f(e){
getElementsInArea(e, {
elements : document.querySelectorAll('div'),
markedClass : 'highlight--1',
zone : [20, 20] // percentage distance from top & bottom
});
getElementsInArea(e, {
elements : document.querySelectorAll('div'),
markedClass : 'highlight--2',
zone : [40, 40] // percentage distance from top & bottom
});
}
Would love all the help I could get. Cheers