Issue
I have a two functions written that works great. One function will add the HTML video attribute autoplay
to the video DOM element, if the user is at a certain section on the page. Another function will slide in some elements with a nice transition.
But the downside is that it will work for one element within page, but I would like to have it work on other elements as well.
Here is one function, the one that play the video on scroll:
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();
}
}
});
}
For now the function does only the work if the section with the id #user-experience
is in view, but it would be great if I can use the function for more sections.
At the moment of writing, I am thinking about to change the target section to a classname and if a section has this class it will do its work. Or is there some better way to do this?
If I take a look at my second function that I mentioned before, that will handle some nice incoming animation on scroll, I doesn't know how to reuse this function for multiple element selectors:
moduleShift: function() {
var root = this;
var el = $('.entry figure');
var offset = 0.8;
root.isVisible(el, offset);
$(window).scroll(function() {
// Get the offset of the window from the top of page
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');
};
});
}
The same solution for above should be able to apply also to this function, but maybe the same question as for the first function, is there a better way to do this?
Solution
You can use jQuery Waypoints. It's propably the easiest way to do that. Your functions isVisible
and moduleShift
should be handlers for events triggered when user scroll to a certain point. For example:
var waypoint = new Waypoint({
element: document.getElementById('placeOfYourVideoPlayer'),
handler: moduleShift;
})
Answered By - M. Twarog
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.