I am trying to get more object-oriented when writing Javascript for (simple) websites. I want to create a new object, vidyo, for each video element on the page while looping through them. Here's what I have right now. This achieves my goals for the function but I know there has to be a better way to organize this code.
I want to be able to call vidyo on $('video') after the loop. I also want to make it more plugin like, so I could possibly add in options.
I tried making vidyo a legitimate object and tried making new instances of it inside the loop but that didn't work.
Any pointers on how to turn these lines into something more robust? Thanks.
var $win = $(window),
top = $win.scrollTop(),
$videos = $('video');
var vidyo = {
play: function(video) {
video[0].play();
},
pause: function(video) {
video[0].pause();
},
check: function(vid) {
var top = $win.scrollTop();
var videoHeight = $(vid).outerHeight(true),
videoHitTop = $(vid).offset().top,
videoOffTheTop = videoHeight + videoHitTop;
if ( top >= videoHitTop && top <= videoOffTheTop ) {
vidyo.play($(vid));
} else {
vidyo.pause($(vid));
}
}
}
var checkVideoPosition = function() {
$videos.each( function( index, el ) {
vidyo.check(el);
})
}
$win.on('scroll', checkVideoPosition);