Skip to content

Instantly share code, notes, and snippets.

@johndwells
Created July 12, 2023 15:57
Show Gist options
  • Save johndwells/227c5bb1968338f6e73f573b785a2291 to your computer and use it in GitHub Desktop.
Save johndwells/227c5bb1968338f6e73f573b785a2291 to your computer and use it in GitHub Desktop.
Play/Pause Vimeo when scrolling into view
/* src/js/app.js */
import Alpine from 'alpinejs';
import intersect from '@alpinejs/intersect';
import video from '@js/parts/alpine/video';
Alpine.plugin(intersect);
Alpine.data("video", video);
window.Alpine = Alpine;
Alpine.start();
{# templates/_includes/embeddedAsset.twig #}
{% set vimeoQuality = vimeoQuality|default('auto') %}
{% if embeddedAsset.type == 'video' and embeddedAsset.providerName == 'Vimeo' %}
<div
x-cloak
x-data='video("{{ embeddedAsset.url }}", {{ { quality : vimeoQuality }|json_encode|raw }})'
x-intersect.half="play()"
x-intersect:leave="pause()">
</div>
{% else %}
<!-- ERROR: either mobile asset was not a video or the provider was not from vimeo -->
{% endif %}
{% set embeddedAsset = craft.embeddedAssets.get(entry.asset.one()) %}
{% if embeddedAssset %}
{% include '_includes/embeddedAsset.twig' with {
embeddedAsset : embeddedAsset,
vimeoQuality : 'auto',
} %}
{% endif %}
/* src/js/parts/alpine/video.js */
import Player from '@vimeo/player';
/**
* Usage:
*
* Step 1: Somewhere in JS...
* import Alpine from "alpinejs";
* import video from "./video";
* Alpine.data('video', video);
* Alpine.start();
*
* Step 2: Somewhere in markup...
* <div x-data="video('url-to-video', { quality : 'auto' })" />
*
* @param src
* @param options
* @returns {{play(): void, init(): void, iframeCont: null, src: string, pause(): void}}
*/
export default (src = '', options = {}) => ({
src: src,
iframeCont: null,
init() {
this.$nextTick(() => {
var opts = {
url: src,
height: this.$el.clientHeight,
width: this.$el.clientWidth,
allowfullscreen: 0,
autopause: 0,
autoplay: 0,
controls: 0,
loop: 1,
muted: 1,
playsinline: 1,
responsive: 0,
quality: 'auto',
...options,
};
console.log(opts);
if (!this.iframeCont) {
var play = new Player(this.$el, opts);
this.iframeCont = play.element;
}
});
},
play() {
this.$nextTick(() => {
var player = new Player(this.$el);
player.play().then(function() {
}).catch(e => console.log(e));
});
},
pause() {
this.$nextTick(() => {
var player = new Player(this.$el);
player.pause().then(function() {
}).catch(e => console.log(e));
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment