Skip to content

Instantly share code, notes, and snippets.

@mujahidi
Created March 19, 2024 14:10
Show Gist options
  • Save mujahidi/822f64c712544f3ab74b06e81cdff998 to your computer and use it in GitHub Desktop.
Save mujahidi/822f64c712544f3ab74b06e81cdff998 to your computer and use it in GitHub Desktop.
Pause video when jQuery SLICK slide changes
<?php
// append custom parameters to YouTube iframe to enable JS API
$custom_parameters = '&amp;rel=0&amp;enablejsapi=1';
// Append custom parameters to the src attribute of the iframe
$modified_iframe = preg_replace('/src="(.*?)"/', 'src="$1' . $custom_parameters . '"', $video_iframe);
// For Vimeo video, make sure to append ?api=1
// https://codepen.io/michaelsmyth94/pen/EVQEQV?editors=0010
//bind our event here, it gets the current slide and pauses the video before each slide changes.
$('.work-slider-for').on('beforeChange', function(event, slick, currentSlide, nextSlide){
var currentSlide, slideType, player, command;
//find the current slide element and decide which player API we need to use.
currentSlide = $(slick.$slider).find(".slick-current");
/**
* determine which type of slide this, via a class on the slide container.
* This reads the second class, you could change this to get a data attribute or
* something similar if you don't want to use classes.
*/
slideType = currentSlide.attr("class").split(" ")[1];
//get the iframe inside this slide.
player = currentSlide.find("iframe").get(0);
if (slideType == "vimeo") {
command = {
"method": "pause",
"value": "true"
};
} else {
command = {
"event": "command",
"func": "pauseVideo"
};
}
//check if the player exists.
if (player != undefined) {
//post our command to the iframe.
player.contentWindow.postMessage(JSON.stringify(command), "*");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment