I was tasked with converting a jQuery function into plain JavaScript. The function is used to check if an element is within the viewport. If it is within the viewport take the data-bglazy attribute and add a background image style to that element using the value of that attribute. The function that needs converted is:
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
$(window).on('resize scroll', function() {
$('.bgLazy').each(function() {
if ($(this).isInViewport()) {
var lazyImg = $(this).attr('data-bglazy');
$(this).css('background-image', 'url(' + lazyImg + ')');
}
});
});
Currently what I have when trying to convert the above function to JavaScript:
function isInViewport(el){
var elementTop = el.offsetTop;
var elementBottom = elementTop + el.offsetHeight;
var viewportTop = window.scrollTop;
var viewportBottom = viewportTop + window.offsetHeight;
return elementBottom > viewportTop && elementTop < viewportBottom;
};
var bgElements = document.querySelectorAll('.bgLazy');
bgElements.forEach(bgElementLoop);
function bgElementLoop(item, index) {
if(item.isInViewport()){
var lazyImg = item.getAttribute('data-bglazy');
item.style.backgroundImage = 'url(' + lazyImg + ')';
}
}
window.addEventListener("resize, scroll", bgElementLoop);
I am trying to figure out which part I screwed up on when attempting to convert the jQuery function to JavaScript
EDIT:
I made a view changes after reading some of the comments. the isInViewport function is not changed, but what I did change is the following:
var bgElements = Array.prototype.slice.call(document.querySelectorAll('.bgLazy'));
bgElements.forEach(bgElementLoop);
function bgElementLoop(item, index) {
if(item.isInViewport(item)){
var lazyImg = item.getAttribute('data-bglazy');
item.style.backgroundImage = 'url(' + lazyImg + ')';
}
}
window.addEventListener("resize", bgElementLoop);
window.addEventListener("scroll", bgElementLoop);
So what I did here is changed the bgElements variable from
var bgElements = document.querySelectorAll('.bgLazy');
to
var bgElements = Array.prototype.slice.call(document.querySelectorAll('.bgLazy'));
I then separated the resize and scroll event listeners into:
window.addEventListener("resize", bgElementLoop);
window.addEventListener("scroll", bgElementLoop);
querySelectorAllreturns aNodeList, not an array.window.addEventListener("resize, scroll", bgElementLoop);you also shouldn't have the comma in the event stringif(item.isInViewport())should beif(isInViewport(item))