Multiple videos with Flexslider v2

Flexslider, is one of my favorite sliders around, I find it useful on several projects.

The one thing that I’ve found it was actually missing, was the ability to have multiple videos working with the vimeo API. For me, a complete headache. The awful sound a video overlapping on top of the other. Complete chaos!

So, reading a bit and after some tryouts I’ve developed a code which makes your slider works without any trouble having several vimeo videos.

You can check the demo here: DEMO

Let’s have a look at the entire code:

jQuery(window).load(function() { 
	var vimeoPlayers = jQuery('.flexslider').find('iframe'), player; 		
	
	for (var i = 0, length = vimeoPlayers.length; i < length; i++) { 		    
			player = vimeoPlayers[i]; 		    
			$f(player).addEvent('ready', ready); 		
	} 		
	
	function addEvent(element, eventName, callback) { 	    	
		if (element.addEventListener) { 		    	
			element.addEventListener(eventName, callback, false) 		    
		} else { 	      		
			element.attachEvent(eventName, callback, false); 	      	
		} 	    
	} 	    
	
	function ready(player_id) { 	    	
		var froogaloop = $f(player_id); 	    	
		froogaloop.addEvent('play', function(data) { 		    	
			jQuery('.flexslider').flexslider("pause"); 		    
		}); 		    
		froogaloop.addEvent('pause', function(data) { 			    
			jQuery('.flexslider').flexslider("play"); 		    
		}); 		
	}  
	
	jQuery(".flexslider")     
	.flexslider({       
		animation: "slide",
		useCSS: false,       
		animationLoop: false,       
		smoothHeight: true,       
		before: function(slider){         
			if (slider.slides.eq(slider.currentSlide).find('iframe').length !== 0)
			      $f( slider.slides.eq(slider.currentSlide).find('iframe').attr('id') ).api('pause');       
		}   
	});

});

Basically, it creates an array containing all the iframes inside the flexslider wrapper. Then, for each player inside those iframes it sets the event. Lastly, when you initialize the flexslider you set a function for the before action that pauses the player that loses focus.

It’s really straightforward. There are a couple of things to bear in mind:

1. Include froogaloop.js

2. You’ll need to revise each vimeo code and check that they have different id’s, and they use the API.


<iframe loading="lazy" id="player_1" src="http://player.vimeo.com/video/39683393?api=1&player_id=player_1" width="320" height="240"></iframe>

3. Enable videos in your flexslider configuration.

4. I think that’s all.

Have fun.

By Juanfra

Juanfra is a WordPress developer. He founded nicethemes.com, he loves food, traveling and music. He's hungry for more!

87 comments

    1. Hi Vedran, which version of safari are you running?
      I’ve tried over v6 and it seems to have the pause between slides while playing.

  1. Hi Juanfra,

    I have tried to incorporate the multi videos into the Flexslider. I have it working fine with images, but when i place 4 videos into the slider it breaks. I have used the code you provided. For some reason it just picks one video and does not slide to any others. The pagination works fine and the nav arrows work as it would with images.

    I have tried removing all other code from the page and that has made no difference, so i don’t think there are any conflicts. I get no console errors either.

    I saved your page and tested locally and it works fine, so this i think it is something to do with the setup, but what i don’t get it why does it work from your site, but when i then copy the exact code from the files into the files i need to you it breaks.

    I don’t know if it has something to do with the width of the elements set in JS vs the width of the element.
    I found that if the videos are set to 500px wide in the iframe code it shows one. If i then set an itemWidth in the Flexsider controls to 214 it shows all 4 videos (but obviously smaller widths).

    I don’t know if this is a bug with Flexsider, or if it is just an issue with my setup?
    If you could shine any light on this it would be great.

    Thanks

  2. Hey Juanfra,

    Thanks for sharing this code.

    I’m having a bit of difficulty getting it to work. I’ve basically copied and pasted your code into my page (http://uberangst.com/services/vfx/). The second, fourth, fifth and sixth slides contain a vimeo video. No matter what I do, I can’t get the video to pause.

    Would you mind having a quick look? I’d be happy to pay you for your time.

    Many thanks,
    Jacob

    1. Hi Jacob,

      Thanks for stopping by, and writing 🙂

      I’ve seen your code and it everything seems ok, except that your using the straight ampersand symbol instead of & when concatenating the player_id parameter. If I’m not wrong, that would make the api not to understand that parameter and as a result, the “pause” action for the video that loses focus won’t work. Let me know if that fix the problem.

      I’m happy to help, if you want you can support my project http://nicethemes.com by spreading the word out there 🙂

      Thanks.
      Juan.

      1. Thanks for including this! They didn’t mention that this script needed to be included on the official flexslider website example for video embeds.

  3. Hi Juanfra,

    Thanks for posting this!

    Unfortunatly I don’t have any luck getting this script to work. I’d very much like to use Flexslider as a simple video showcase but the pause function is quite essential. I’ll admit, my knowledge of scripting doesn’t really reach beyond html/css but I like to try different things. My website is located here: http://laurensmooiweer.nl

    Would you be so kind and take a look? I’m probably making some obvious mistake but I can’t see it.

    Thanks!

    1. Hi Laurens,

      thanks for writing 🙂 BTW: Great videos out there, good job man!

      I’ve seen your code and you’re triggering two times the flexslider function. Plus, the code for the multiple videos is outside the <body> html tag. You should move that code above the </body> closing tag.

      I hope this helps.

      All the best!
      Juanfra.

      1. Hi!

        Thanks for the quick reply. I’ve removed the first trigger and replaced it with your script. Only now the whole flexslider stopped working and I have no idea why. Any thoughts?

        Best,

        1. Hi Laurens,

          The first error I see is that froogaloop isn’t loading well. It’s loading an HTML instead of a JS. Also the order in which you’re loading your JS libraries is not correct.

          I’ll send you a new file to your email.

          Best,
          Juan.

  4. The Vimeo embed code does not have the “api=1&player_id=player_1” stuff added, did you add this? Is there a way to simply use the embed code that Vimeo gives you without adding the unique id’s to the iframe – perhaps adding the id’s to the .

    I would like to populate the gallery dynamically, and it would be easy to give id’s to the element, but not easy to add it to the iframe content, and append the “api=1&player_id=player_1” to the end of the Src.

    1. Yes, that code was added by hand. It wouldn’t be possible to handle the video events without using vimeo’s API and without having an id for each video.

      Have in mind that the script is pausing the slide video whenever a new slide comes to the front.

  5. Great stuff. I do have a question though. It seems that the code stops working when animationLoop is set to true. If I have 3 videos, it will work the first round. When I go from video 3 to video 1 again, video 3 will not stop playing. Is there a way to add this in? Or will it simply not work with the animationLoop no matter what?

    Thanks.

    1. Thanks Sabine 🙂

      To be honest, I haven’t tried with animationLoop set to true. Anyway, I find it strange that it isn’t working, because the pause event is set for the current slide, before it changes (saying this, I mean it won’t be a problem to jump from the last to the first one. As the action is set to the current slide)

      Do you have any URL so I can have a look?

      1. I created 2 static pages for you.
        1) http://fokuspoint.com/VMTest/multiple-videos-flexslider-v2.htm
        It’s a copy of your demo. I created a local copy and turned the animationLoop on. Click on your last video link, play it, then click on the first one. It keeps playing
        2) http://fokuspoint.com/VMTest/VimeoTest.html
        This is essentially the same but the slide show keeps looping. When the video plays it stops. Play the last video (2012…) then click on the right arrow and the video keeps playing. If you do that with the 1st or 2nd video it stops as expected.

        I would have expected that the player stops no matter which video I’m on, since it should have the 3 video IDs in the array, right? Is it maybe looking for ID4?

        Thanks.

        1. Thanks Sabine.

          I’ve been looking to both pages. I’ve set up a new test environment locally and I don’t find any logical reason of why this isn’t working.

          I mean, the pause action is triggered the same way for all of the iframes inside each slide. There’s no error of ID or similar. I don’t understand, I can imagine that there’s some special treatment for the last slide from flexslider when the slider is looping. Anyway, the pause method is called. I’m sorry I can’t help you on this ):

          1. I downloaded flexslider from their website and set up the Vimeo example with only two things changed. Firstly I set the slideshow to loop and secondly I put the video in the last position. It didn’t work properly at all, not pausing the slideshow when I clicked on the video. I thought I’d report here that as far as I could see it this is a bug with flexslider, ( as I wasn’t using any of the code from this page, just flexslider’s example code ) .

          2. Hi Byron,

            Thanks for writing. Yes, that happens when you set the slideshow to loop. Please check this comment where Adam suggest a solution 🙂

            Best,
            Juanfra.

  6. Hellooo!!! You’re great!!
    …and what happend if I want to use a You Tube Video??
    what can I do??

    Thanks a lot!!!

          1. Hi Manu,

            That has to do with your CSS. You should review the CSS for your li tags. The following code should solve your problem:


            .flexslider .slides > li {
            margin: 0;
            }

            Best,
            Juan.

  7. Erm, ok. So i download the demo from Flexslider. Do i replace any of the JS with yours? Or do i just add your JS too?

    The demo comes with froogaloop and fitvid, they are just not called. So calling them now, but where do i put your JS?

    Thanks

    1. Hello Ollie,

      I’m not sure how the demo is these days, I would recommend you put this JS when initializing the flexslider.

      The demo script should have a few lines like these:

      jQuery(".flexslider").flexslider({ // maybe some options here 
                                                        });
      

      Best,
      Juan.

  8. Going out on a limb here. I’m pretty good with this stuff. But with the code properly in place, and after testing that all variables are being passed correctly. I can’t get the script to stop anything but the first video to stop playing. First video works fine, every other video keeps playing after slide transition. I can not post code since it is for a client, but I was just wondering if you might have some insight as to why this might be happing. Any help would be appreciated.

    1. Hey there,

      There’s a bug on flexslider for the before function when the autoloop is set to true. Please check this.

      Best,
      Juanfra.

    2. figured out the problem. Flex slider creates a clone of the first and last slides in the slideshow if animationLoop is set to true. If one of those slides has a video in it the id is being duplicated as well. Vimeo api can not stop a video if there are two videos with the same id in the DOM. Simple fix is to remove the id from the iframe in the cloned . Just add a jQuery call after the .flexslider call to remove the id attribute from the cloned iframe and it works perfect. This should also take care of the above issue with your code not working on AnimationLoop: True in the flexslider settings.

  9. Sorry to keep bothering you. I also have this working with YouTube videos if you’d like the code. Let me know. Still some issues with going to next slide when youtube video finishes but it shouldn’t be too hard to implement.

    1. Sure man, I’ll drop you a line so we can coordinate and maybe include it here 😉 I remember somebody asked me about integrating this with youtube.

  10. I’ve also got multiple-videos for YouTube working concurrently with your code (with two small tweaks). It’s a bit rough around the edges (haven’t bothered cleaning them code up from getting it working), but I’d be happy to compare notes with what Adam has.

  11. I ama interested in getting this working with multiple youtube videos as well – if you could post that solution here that would be great!

    Thanks,
    Greg

  12. Would be awesome if you could drop a line with a unfinished (not perfect:) work around for the Youtube version. Tried this one, but seems to be not to work.

    1. Hey there, thanks for sharing this. I’ve seen some familiar code over that thread, haha 🙂

      I’ll be putting things together soon. I know there are some people interested on this.

      Best,
      Juanfra.

    1. Hi There,

      There’s something out there. I didn’t have time to combine what I’ve done for vimeo + youtube yet 🙂

  13. Hi Juanfra
    This is a great piece of code. Could you let me know when you have added Adam Weston’s suggestion to remove the id tag from the iframe in the clone, when using animationLoop: true. It is causing me the same problems as the others.

    Thanks

  14. Hi there! Thanks for this. Well, I’m getting quite frustrated. I can’t figure out what I’m doing wrong. But I can’t get a playing video to stop playing when going to s different slide. This seems to work on both your demo and the FlexSlider demo… but I can’t get it to work when I try using the same code. What am I doing wrong?

    Also, when you say “Enable videos in your flexslider configuration.” — where is that? I don’t see that anywhere.

    Would super-appreciate your help!

    Doug

    1. Hi Doug,

      Thanks for writing – I’ve seen you also wrote me on twitter 🙂 Do you still have trouble with it?

      Best,
      Juanfra.

  15. Hi Juanfra, I copy your example, but the slider does not stop when I run a video, and I can send you the source to determine what could be the problem, and sorry for the inconvenience.

    1. Hi Douglas,

      Have you tested if there’s any error in the console? Maybe some dependencies are missing. You can send the code over juan at nicethemes dot com, I can’t guarantee that I’ll be having time these days, though. I’m travelling at the moment.

      Thanks for stopping by,
      Juanfra

  16. Hi Juanfra,

    Your code works perfectly, just wonder if we can autoplay the video when the video slide is active.

    I have a mixture of pictures and videos. When user goto Video slide from Picture slide, I would like it to play automatically.

    I would really appreciate your reply.

    Thanks,
    Jimba

    1. Hi Jimba,

      Thanks for writing. Yes, I didn’t do it but I’m sure it’s possible. You’ll need to try to add a little coding for the before: function, look for the current slide and apply the .api('play'); action.

      That would be:

      before: function(slider){
      if (slider.slides.eq(slider.currentSlide).find('iframe').length !== 0)
      $f( slider.slides.eq(slider.currentSlide).find('iframe').attr('id') ).api('pause');

      $f(findthecurrentslide).api('play');
      }

      Try to find the current slide iframe and replace it on ‘findthecurrentslide’.

      Cheers,
      Juanfra.

    1. Hi There,

      Thanks for writing. Unfortunately I didn’t have enough time to review this code lately. I’ve been moving a lot.

      Juanfra.

  17. you code is perfect, just one problem , i am using vimeo player to auto play video

    Problem is it does not pause player , and slider keep rotating while video played half of the duration

    Can you please help me how to pause slider until video is fully played with a auto play video

    Thanks

  18. Hi Juanfra,

    First of all thanks for sharing this code.

    Well, I need your help on resetting video frame once it’s played so once slider come to same video again it shows the starting or default frame of video and not the end position.

  19. Hello Juanfra

    Thank you for sharing this code.
    I actually have 4 images and 2 videos in a flexslider. I used the code that you shared above but the flexslider dosen’t pause when a video is played. Could you please help me on this problem?

    Thanks

    1. Hello Kavya,

      Thanks for leaving a comment.

      Do you actually get some sort of error in your console? Did you follow all the steps described in the post?

      Cheers,
      J.

      1. Hello Juanfra

        Thank you for the reply. Yes, I have followed all the steps as described in the post. I’m not getting any errors in the console either. I have tried all possible solutions mentioned on various sites to resolve this issue but nothing seems to work. Would you be kind enough to take a look at the source code if I sent it to you as the site is not yet hosted?

        Thanks
        Kavya

  20. Hey Guys,

    Just found a very simple way to resolve the problem for youtube vidéo. It’s dirty but youtube don’t give us a way to resolve the problem.

    Add this just before your where spacer.gif is a transparent image

    For me it works perfect!!

Leave a comment

Your email address will not be published. Required fields are marked *