Two functions have been implemented successfully. One function adds the autoplay
attribute to a video DOM element if the user is at a specific section on the page. The other function smoothly slides in elements with a transition effect.
The only limitation is that these functions currently work for only one element on the page, but I wish to extend their functionality to multiple elements.
Here is the first function, which plays the video when scrolled:
playOnScroll: function() {
var player = $('.browser video');
var hasReached = false;
function isInView(elem){
return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
}
$(window).scroll(function() {
var section = $('#user-experience');
// If section exists
if (section.length) {
if (isInView(section) && !hasReached) {
// console.log('play video');
hasReached = true;
player.get(0).play();
}
}
});
}
Currently, this function only works if the section with the ID #user-experience
is in view. It would be beneficial if it could be applied to other sections as well.
I am considering changing the target section to a class name so that any section with this class can trigger the function. Is there a better approach?
Now, looking at the second function responsible for animating elements upon scroll, I am unsure how to make it reusable for multiple selectors:
moduleShift: function() {
var root = this;
var el = $('.entry figure');
var offset = 0.8;
root.isVisible(el, offset);
$(window).scroll(function() {
var windowPos = $(this).scrollTop();
setTimeout(function(){
root.isVisible(el, offset);
}, 1000);
});
},
isVisible: function(el, offset) {
el.each(function() {
var elHeight = $(this).outerHeight();
var offsetTop = $(this).offset().top;
var offsetBottom = offsetTop + elHeight;
if (offsetTop <= $(window).scrollTop() + $(window).height()*offset) {
$(this).addClass('moduleShift');
};
});
}
A similar solution may be applicable to this function as well. However, like the first function, I am open to suggestions for a more efficient method of achieving this.