Skip to content

Instantly share code, notes, and snippets.

@tommydunn
Last active March 12, 2024 12:58
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save tommydunn/1a8e43fef57059cc5197d02890d1a886 to your computer and use it in GitHub Desktop.
Save tommydunn/1a8e43fef57059cc5197d02890d1a886 to your computer and use it in GitHub Desktop.
Slick Slider with auto play YouTube, Vimeo and HTML5 video
<header>
<h1>SITE TITLE</h1>
<nav>
<ul>
<li><a href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">SERVICES</a></li>
<li><a href="#">CONTACT</a></li>
</ul>
</nav>
</header>
<section class="main-slider">
<div class="item image">
<span class="loading">Loading...</span>
<figure>
<div class="slide-image slide-media" style="background-image:url('https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLRkY4S0JDTk1BbE0');">
<img data-lazy="https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLRkY4S0JDTk1BbE0" class="image-entity" />
</div>
<figcaption class="caption">Static Image</figcaption>
</figure>
</div>
<div class="item vimeo" data-video-start="4">
<iframe class="embed-player slide-media" src="https://player.vimeo.com/video/217885864?api=1&byline=0&portrait=0&title=0&background=1&mute=1&loop=1&autoplay=0&id=217885864" width="980" height="520" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<p class="caption">Vimeo</p>
</div>
<div class="item image">
<figure>
<div class="slide-image slide-media" style="background-image:url('https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLNXBIcEdOUFVIWmM');">
<img data-lazy="https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLNXBIcEdOUFVIWmM" class="image-entity" />
</div>
<figcaption class="caption">Static Image</figcaption>
</figure>
</div>
<div class="item youtube-sound">
<iframe class="embed-player slide-media" width="980" height="520" src="https://www.youtube.com/embed/QV5EXOFcdrQ?enablejsapi=1&controls=0&fs=0&iv_load_policy=3&rel=0&showinfo=0&loop=1&playlist=QV5EXOFcdrQ&start=1" frameborder="0" allowfullscreen></iframe>
<p class="caption">YouTube w/ sound</p>
</div>
<div class="item youtube">
<iframe class="embed-player slide-media" width="980" height="520" src="https://www.youtube.com/embed/QV5EXOFcdrQ?enablejsapi=1&controls=0&fs=0&iv_load_policy=3&rel=0&showinfo=0&loop=1&playlist=QV5EXOFcdrQ&start=1" frameborder="0" allowfullscreen></iframe>
<p class="caption">YouTube w/out sound</p>
</div>
<div class="item image">
<figure>
<div class="slide-image slide-media" style="background-image:url('https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLSlBkWDBsWXJNazQ');">
<img data-lazy="https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLSlBkWDBsWXJNazQ" class="image-entity" />
</div>
<figcaption class="caption">Static Image</figcaption>
</figure>
</div>
<div class="item video">
<video class="slide-video slide-media" loop muted preload="metadata" poster="https://drive.google.com/uc?export=view&id=0B_koKn2rKOkLSXZCakVGZWhOV00">
<source src="https://player.vimeo.com/external/138504815.sd.mp4?s=8a71ff38f08ec81efe50d35915afd426765a7526&profile_id=112" type="video/mp4" />
</video>
<p class="caption">HTML 5 Video</p>
</div>
</section>
<section class="container">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit beatae rerum ratione, voluptates nisi magni delectus ab, eaque atque iste. Molestias incidunt nemo veniam alias nam nisi distinctio optio error architecto odit! Illo dicta nulla fugiat distinctio laudantium, corrupti eum unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit beatae rerum ratione, voluptates nisi magni delectus ab, eaque atque iste. Molestias incidunt nemo veniam alias nam nisi distinctio optio error architecto odit! Illo dicta nulla fugiat distinctio laudantium, corrupti eum unde. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit beatae rerum ratione, voluptates nisi magni delectus ab, eaque atque iste. Molestias incidunt nemo veniam alias nam nisi distinctio optio error architecto odit! Illo dicta nulla fugiat distinctio laudantium, corrupti eum unde.</p>
</div>
</section>
var slideWrapper = $(".main-slider"),
iframes = slideWrapper.find('.embed-player'),
lazyImages = slideWrapper.find('.slide-image'),
lazyCounter = 0;
// POST commands to YouTube or Vimeo API
function postMessageToPlayer(player, command){
if (player == null || command == null) return;
player.contentWindow.postMessage(JSON.stringify(command), "*");
}
// When the slide is changing
function playPauseVideo(slick, control){
var currentSlide, slideType, startTime, player, video;
currentSlide = slick.find(".slick-current");
slideType = currentSlide.attr("class").split(" ")[1];
player = currentSlide.find("iframe").get(0);
startTime = currentSlide.data("video-start");
if (slideType === "vimeo") {
switch (control) {
case "play":
if ((startTime != null && startTime > 0 ) && !currentSlide.hasClass('started')) {
currentSlide.addClass('started');
postMessageToPlayer(player, {
"method": "setCurrentTime",
"value" : startTime
});
}
postMessageToPlayer(player, {
"method": "play",
"value" : 1
});
break;
case "pause":
postMessageToPlayer(player, {
"method": "pause",
"value": 1
});
break;
}
} else if (slideType === "youtube-sound") {
switch (control) {
case "play":
postMessageToPlayer(player, {
"event": "command",
// "func": "mute"
});
postMessageToPlayer(player, {
"event": "command",
"func": "playVideo"
});
break;
case "pause":
postMessageToPlayer(player, {
"event": "command",
"func": "pauseVideo"
});
break;
}
} else if (slideType === "youtube") {
switch (control) {
case "play":
postMessageToPlayer(player, {
"event": "command",
"func": "mute"
});
postMessageToPlayer(player, {
"event": "command",
"func": "playVideo"
});
break;
case "pause":
postMessageToPlayer(player, {
"event": "command",
"func": "pauseVideo"
});
break;
}
} else if (slideType === "video") {
video = currentSlide.children("video").get(0);
if (video != null) {
if (control === "play"){
video.play();
} else {
video.pause();
}
}
}
}
// Resize player
function resizePlayer(iframes, ratio) {
if (!iframes[0]) return;
var win = $(".main-slider"),
width = win.width(),
playerWidth,
height = win.height(),
playerHeight,
ratio = ratio || 16/9;
iframes.each(function(){
var current = $(this);
if (width / ratio < height) {
playerWidth = Math.ceil(height * ratio);
current.width(playerWidth).height(height).css({
left: (width - playerWidth) / 2,
top: 0
});
} else {
playerHeight = Math.ceil(width / ratio);
current.width(width).height(playerHeight).css({
left: 0,
top: (height - playerHeight) / 2
});
}
});
}
// DOM Ready
$(function() {
// Initialize
slideWrapper.on("init", function(slick){
slick = $(slick.currentTarget);
setTimeout(function(){
playPauseVideo(slick,"play");
}, 1000);
resizePlayer(iframes, 16/9);
});
slideWrapper.on("beforeChange", function(event, slick) {
slick = $(slick.$slider);
playPauseVideo(slick,"pause");
});
slideWrapper.on("afterChange", function(event, slick) {
slick = $(slick.$slider);
playPauseVideo(slick,"play");
});
slideWrapper.on("lazyLoaded", function(event, slick, image, imageSource) {
lazyCounter++;
if (lazyCounter === lazyImages.length){
lazyImages.addClass('show');
// slideWrapper.slick("slickPlay");
}
});
//start the slider
slideWrapper.slick({
// fade:true,
autoplaySpeed:4000,
autoplay: true,
lazyLoad:"progressive",
speed:600,
arrows:false,
dots:true,
cssEase:"cubic-bezier(0.87, 0.03, 0.41, 0.9)"
});
});
// Resize event
$(window).on("resize.slickVideoPlayer", function(){
resizePlayer(iframes, 16/9);
});
<script src="//code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.js"></script>

Slick Slider with auto play YouTube, Vimeo and HTML5 video

This sample is the tips for slick slider including YouTube, Vimeo and HTML5 video player. Each video plays automatically when the video slide has shown. And the slider fits the browser width.

A Pen by tommydunn on CodePen.

Original forked from digistate

$fonts: Arial, "Hiragino Kaku Gothic Pro W3", Meiryo, sans-serif;
$bg_color: #2d3042;
$font_color: #efefef;
$link_color: #efefef;
$link_hover_color: #fff;
*, *:before, *:after {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: $fonts;
background-color: $bg_color;
position: relative;
color: $font_color;
text-align: center;
a, a:visited {
color: $link_color;
text-decoration: none;
}
a:hover {
color: $link_hover_color;
}
}
%bv_hidden {
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
}
%filled_obj {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
header {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 60px;
padding: 0 5%;
text-align: left;
z-index: 1;
h1 {
display: inline-block;
font-size: 22px;
font-weight: bold;
padding-top: 18px;
}
nav {
display: inline-block;
float: right;
ul {
li {
display: inline-block;
vertical-align: top;
font-size: 13px;
a {
display: block;
padding: 24px 15px;
&:hover {
background-color: rgba(#fff, .18);
}
}
}
}
}
}
.main-slider {
position: relative;
width: 100%;
height: 38vw;
min-height: 8vw;
margin-bottom: 50px;
opacity: 0;
visibility: hidden;
transition:all 1.2s ease;
&.slick-initialized {
opacity: 1;
visibility: visible;
}
}
.slick-slide {
position: relative;
height: 38vw;
@extend %bv_hidden;
&::before {
@extend %filled_obj;
@extend %bv_hidden;
background-color: #000;
opacity: .3;
z-index: 1;
}
video {
display: block;
position: absolute;
top: 50%;
left: 50%;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
transform:translate(-50%, -50%);
}
iframe {
position: relative;
pointer-events: none;
}
figure {
position: relative;
height: 100%;
}
.slide-image {
opacity: 0;
height: 100%;
background-size: cover;
background-position: center;
// background-color:rgba(#c46897,.38);
// background-blend-mode:overlay;
transition:all .8s ease;
&.show {
opacity: 1;
}
}
.image-entity {
width: 100%;
opacity: 0;
visibility: hidden;
}
.loading {
position: absolute;
top: 44%;
left: 0;
width: 100%;
}
.slide-media {
animation:slideOut .4s cubic-bezier(0.4, 0.29, 0.01, 1);
}
&.slick-active {
z-index: 1;
.slide-media {
animation:slideIn 2.4s cubic-bezier(0.4, 0.29, 0.01, 1);
}
.caption {
opacity: 1;
transform:translateY(0);
transition:all .7s cubic-bezier(0.32, 0.34, 0, 1.62) .6s;
}
}
}
.caption {
position: absolute;
top: 44%;
left: 5%;
text-align: center;
padding: 20px;
border: 3px solid;
color: #fff;
margin: 0;
font-size: 40px;
font-weight: bold;
letter-spacing: .02em;
opacity: 0;
z-index: 1;
transition:all .3s ease;
transform:translateY(100px);
@extend %bv_hidden;
}
.slick-dots {
text-align: center;
padding-top: 15px;
li {
display: inline-block;
vertical-align: top;
margin: 0 8px;
button {
width: 16px;
height: 16px;
border: none;
cursor: pointer;
border-radius: 50%;
border: 2px solid #fff;
box-shadow: 0 0 0 0 transparent;
vertical-align: middle;
color: #fff;
background-color: #fff;
transition:all .3s ease;
opacity: .4;
&:focus {
outline: none;
}
&:hover {
opacity: 1;
}
}
&.slick-active {
button {
border-color: $bg_color;
box-shadow: 0 0 0 2px #fff;
opacity: 1;
}
}
}
}
.container {
background-color: #f2f2f2;
color: #444;
line-height: 1.6;
padding: 40px 0;
.content {
width: 90%;
max-width: 980px;
margin: 0 auto;
}
p {
margin-bottom: 40px;
}
}
@keyframes slideIn {
from {
filter:blur(15px);
}
to {
filter:blur(0);
}
}
@keyframes slideOut {
from {
filter:blur(0);
}
to {
filter:blur(15px);
}
}
<link href="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css" rel="stylesheet" />
@lesterdefreitas
Copy link

Any reason why YouTube autoplay would not be working? Vimeo autoplays fine.

@tommydunn
Copy link
Author

tommydunn commented Sep 7, 2019

Any reason why YouTube autoplay would not be working? Vimeo autoplays fine.

This isn't actually autoplay. The trick here is to call the play event when the during the slide callback.

  slideWrapper.on("afterChange", function(event, slick) {
    slick = $(slick.$slider);
    playPauseVideo(slick,"play");
  });

This still works: https://codepen.io/digistate/pen/MvapbE?editors=0010

@Cregdav
Copy link

Cregdav commented Nov 7, 2019

Is there a way to unMute the youtube videos? Are we targeting the iframe here or do we have to go through the API?

@tommydunn
Copy link
Author

tommydunn commented Nov 10, 2019

Is there a way to unMute the youtube videos? Are we targeting the iframe here or do we have to go through the API?

@Cregdav - standard embed. To unmute the video, simply remove "func": "mute" function.

full example:

else if (slideType === "youtube") {
    switch (control) {
      case "play":
        postMessageToPlayer(player, {
          "event": "command",
          // Because  unmuted is the default behavior
         // all you need to do is remove the below 
         // "func": "mute"
        });
        postMessageToPlayer(player, {
          "event": "command",
          "func": "playVideo" 
        });
        break;
      case "pause":
        postMessageToPlayer(player, {
          "event": "command",
          "func": "pauseVideo"
        });
        break;
    }
  }

@rjlewie
Copy link

rjlewie commented Dec 1, 2019

Is there a way to enable the youtube controls again?

@tommydunn
Copy link
Author

Is there a way to enable the youtube controls again?

@rjlewie - this example uses the controls=0 (see below) parameter so you would need to update that in order to show the controls again. I would suggest looking through the YT player documentation for a better option.

    <iframe class="embed-player slide-media" width="980" height="520" src="https://www.youtube.com/embed/QV5EXOFcdrQ?enablejsapi=1&controls=0&fs=0&iv_load_policy=3&rel=0&showinfo=0&loop=1&playlist=QV5EXOFcdrQ&start=1" frameborder="0" allowfullscreen></iframe>

@natalie-v
Copy link

natalie-v commented Feb 20, 2020

I'm having trouble getting the HTML5 video to play when it is the current slide, and then stop playing when the next slide is triggered. Is there a way to do this?

@joelton-ding
Copy link

May i know how i can on the youtube music? Thank for help.

@joelton-ding
Copy link

Is there a way to unMute the youtube videos? Are we targeting the iframe here or do we have to go through the API?

@Cregdav - standard embed. To unmute the video, simply remove "func": "mute" function.

full example:

else if (slideType === "youtube") {
    switch (control) {
      case "play":
        postMessageToPlayer(player, {
          "event": "command",
          // Because  unmuted is the default behavior
         // all you need to do is remove the below 
         // "func": "mute"
        });
        postMessageToPlayer(player, {
          "event": "command",
          "func": "playVideo" 
        });
        break;
      case "pause":
        postMessageToPlayer(player, {
          "event": "command",
          "func": "pauseVideo"
        });
        break;
    }
  }

I try to hide the "func": "mute" but the youtube still don't have the sound.
Please advise.

@tommydunn
Copy link
Author

I try to hide the "func": "mute" but the youtube still don't have the sound.
Please advise.

@joelton-ding = I just tested it and it works: Check out this pen.

@joelton-ding
Copy link

joelton-ding commented Jul 20, 2020 via email

@brytmill
Copy link

Hey Tommy,

Thanks for this, great work. I'm trying to work out how to autoplay youtube in the first slide on load without using the url parameter autoplay=1. Because slick slider clones slides when infinite: true, this causes the current slide video on page load and the cloned slide video to autoplay, causing duplicate audio on page load.The videos do play on transition but how can we activate the current slick slide video on page load?

Thank you,
Bryan

@tommydunn
Copy link
Author

Hey Tommy,

Thanks for this, great work. I'm trying to work out how to autoplay youtube in the first slide on load without using the url parameter autoplay=1. Because slick slider clones slides when infinite: true, this causes the current slide video on page load and the cloned slide video to autoplay, causing duplicate audio on page load.The videos do play on transition but how can we activate the current slick slide video on page load?

Thank you,
Bryan

Hey @brytmill - you could use the current slide variable currentSlide = slick.find(".slick-current"); with the slide type variable slideType = currentSlide.attr("class").split(" ")[1]; to change the autoplay attribute only on the current slide that has slide type === youtube.

@brytmill
Copy link

Hey Tommy,
Thanks for this, great work. I'm trying to work out how to autoplay youtube in the first slide on load without using the url parameter autoplay=1. Because slick slider clones slides when infinite: true, this causes the current slide video on page load and the cloned slide video to autoplay, causing duplicate audio on page load.The videos do play on transition but how can we activate the current slick slide video on page load?
Thank you,
Bryan

Hey @brytmill - you could use the current slide variable currentSlide = slick.find(".slick-current"); with the slide type variable slideType = currentSlide.attr("class").split(" ")[1]; to change the autoplay attribute only on the current slide that has slide type === youtube.

Excellent, thank you!

@satiroglumustafa
Copy link

@tommydunn Thanks for this, great work. However, there are some things I want to do. First of all it works fine when you add the autoplay feature. There is no problem. I give it 4 seconds and all slides change automatically in 4 seconds. The point I want you to help with is this: When it comes to both Youtube and html5 video item, the autoplay feature will be disabled. When the video time is over, the autoplay feature will be activated again. How can I do that?

@tommydunn
Copy link
Author

@tommydunn Thanks for this, great work. However, there are some things I want to do. First of all it works fine when you add the autoplay feature. There is no problem. I give it 4 seconds and all slides change automatically in 4 seconds. The point I want you to help with is this: When it comes to both Youtube and html5 video item, the autoplay feature will be disabled. When the video time is over, the autoplay feature will be activated again. How can I do that?

@satiroglumustafa - Is there a reason why you want autoplay rather than just controlling the playPauseVideo(slick,"play"); and the playPauseVideo(slick,"pause"); event? This doesn't use autoplay.

@despecial
Copy link

Hi @tommydunn thanks for the gist - very helpful.
I found some issues and wanted to share them, so you can make the code more stable. Instead of the old slick script, I am using the accessible fork which shouldn't modify the functions, etc.

Here are the problems I encountered:
1.) slideType is always slide-current
Fix: slideType = currentSlide.find(".item").attr("class").split(" ")[1];

2.) slideType video is undefined
Fix: video = currentSlide.find("video").get(0);

3.) If first slide is a video/youtube clip, it needs to be started manually
Fix: you suggested to change the attribute to autoplay. Will try that.

@speeday
Copy link

speeday commented Feb 24, 2021

I try to hide the "func": "mute" but the youtube still don't have the sound.
Please advise.

@joelton-ding = I just tested it and it works: Check out this pen.

Hi @tommydunn, Is this real working now to mute and unmute the video also as I didn't found it.

Please confirm it once..

@tommydunn
Copy link
Author

I try to hide the "func": "mute" but the youtube still don't have the sound.
Hi @tommydunn, Is this real working now to mute and unmute the video also as I didn't found it.

Please confirm it once..

@speeday - I can confirm this in fact does work. https://codepen.io/tommydunn/pen/rNxQLNq

@speeday
Copy link

speeday commented Feb 24, 2021

Hi @tommydunn, yes it worked on Brave Browser and Firefox Browser but did it worked on Other Browser Like Google Chrome and Safari Browser as well as..?

@speeday
Copy link

speeday commented Feb 28, 2021

@tommydunn, Hope you looked into it as I really didn't found as working for Google Chrome and Safari Browser..?

So please confirm it once.

@tommydunn
Copy link
Author

@tommydunn, Hope you looked into it as I really didn't found as working for Google Chrome and Safari Browser..?

So please confirm it once.

@speeday - chrome works for me: https://codepen.io/tommydunn/live/rNxQLNq

@speeday
Copy link

speeday commented Mar 18, 2021

Thanks @tommydunn, It worked.

@sanjay-makwana-avidbrio
Copy link

sanjay-makwana-avidbrio commented Jun 15, 2021

@tommydunn thanks for the awesome example. it was a superb

I try the example, so the first video takes some to load, when displaying the video on the first slider after some seconds it was skipped on-time start from 5,6 video duration, I want to show the full video on the first Slide. (this issue was smaller but i think internet issue but all web user don't have the high speed )

  • I change the code slideWrapper.on("beforeChange", function(event, slick) { slick = $(slick.$slider); playPauseVideo(slick,"play"); });
  • first video, not autoplay
  • if it was possible to set auto slider duration based on the video duration?
    here code demo
    https://codepen.io/sanjay-m/pen/poeqZYB

@tommydunn
Copy link
Author

@tommydunn thanks for the awesome example. it was a superb

I try the example, so the first video takes some to load, when displaying the video on the first slider after some seconds it was skipped on-time start from 5,6 video duration, I want to show the full video on the first Slide. (this issue was smaller but i think internet issue but all web user don't have the high speed )

  • I change the code slideWrapper.on("beforeChange", function(event, slick) { slick = $(slick.$slider); playPauseVideo(slick,"play"); });
  • first video, not autoplay
  • if it was possible to set auto slider duration based on the video duration?
    here code demo
    https://codepen.io/sanjay-m/pen/poeqZYB

@Sanjayavidbrio - That's a good point. Let me take a look at it and think through a solution (prob won't be till next week).

Thanks!

@sanjay-makwana-avidbrio

@tommydunn Sure Thanks lot

@kapilsipl
Copy link

@tommydunn,
Great work!!
Facing some small challenges, if you could help so it would be much appreciate.

  1. Slide change without play full video (in case of autoplay)
  2. Auto play video not working on slide change, using HTML5 video tag.
    It would be great if you or anyone can help on same.
    thanks in advance.

@theramanpratap
Copy link

is there any way if we can add the external mute/unMute buttons for each video?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment