Created
September 16, 2016 16:03
-
-
Save maxrolon/47f51817b1db2518ed97e51e2ca9470e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scroll from './../lib/scrollListener' | |
const Velocity = require('velocity-animate') | |
require('velocity-ui') | |
const inViewport = el => { | |
let rect = el.getBoundingClientRect() | |
return (rect.top < rect.height) && (rect.top + rect.height > 0) | |
} | |
const merge = defaults => overwrites => { | |
Object.keys(overwrites).forEach( val => { | |
defaults[val] = overwrites[val] | |
}) | |
return defaults | |
} | |
const testState = el => el.readyState == 4 | |
const setSrc = el => el.setAttribute('src', el.getAttribute('data-src') ) | |
const addClass = (cssClass, el) => el.classList.add(cssClass) | |
const fadeIn = el => { | |
let innerEl = document.querySelector('.js-hero-inner') | |
Velocity(el.parentNode, "fadeIn", {duration:2000, delay:500}) | |
Velocity(innerEl, "transition.slideUpIn", {duration: 1500}) | |
} | |
export default (el, opts) => { | |
const settings = merge({ | |
readyClass:'video-ready', | |
parentEl:el.parentNode, | |
autoload:true, | |
fadeIn:fadeIn | |
})(opts) | |
let revealed = false | |
let ready = false | |
let paused = true | |
let play = () => { | |
if (ready && paused){ | |
paused = false | |
el.play() | |
} | |
} | |
let pause = () => { | |
if (!paused){ | |
paused = true | |
el.pause() | |
} | |
} | |
let setReady = (value) => { | |
if (!value) return | |
if ( inViewport(el) ) play(el) | |
if (!revealed){ | |
revealed = true | |
settings.fadeIn(el) | |
} | |
ready = value | |
} | |
//Add src immediately | |
if (settings.autoload) setSrc(el) | |
scroll( (y, prevY) => { | |
if ( inViewport(el) ){ | |
if ( !el.getAttribute('src') ){ | |
setSrc(el) | |
} | |
play(el) | |
} else { | |
pause(el) | |
} | |
}) | |
;['canplaythrough','canplay'].forEach( event => { | |
el.addEventListener(event, () => { | |
setReady( testState(el) ) | |
}) | |
}) | |
setReady( testState(el) ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A small module that automates the play and pause of videos based on scroll position of the user. If you need to simply play a video when it is in view of the user and pause it when not, this module is your guy!
Dependencies
This example uses the RAFScroll library to replace
window.addEventListener('scroll', function(e) {..
native usage. Replace if you want a simple but less performant option. We also use the Velocity animation library to fade in the video. Again, replace this with another form of animation if you need!Settings
Usage
InitScripts.js instantiation (no options supplied)
Vanilla JS instantiation