Tuesday, September 25, 2012

Blueberry (Image slider) and YouTube video working in harmony

Do what needs to be done

We recently launched a new home page and the designed used a responsive image slider called Blueberry. Well there were a few issues with navigation and I needed to be able to make sure to have the slider start to slide automatically and then stop while playing a YouTube video.

I need to fix the problem with navigation causing a speed up and unreliable timing while showing slides. I extended it to support being stopped and started. Since the project appears to be on hiatus (no changes in a year even though it has a few github issues), I forked it on github to fix the event issue and add the ability to stop/start slider.

Blueberry + YouTube sitting in a tree

I found it to be a bit of challenge to update the site to support pausing the image slider when the YouTube video that is linked in through iframe started and stop being played. I found to get the correct permissions and callback into the player I needed to use the YouTube iFrame Player API. (thank you Google)

To setup the Blueberry slider, there is some basic html
(and css see: https://github.com/lecar-red/Blueberry/blob/master/index.html).

Here is a blurb of html


Next is the Javascript code to setup the slider:

$(function() {
  $('.blueberry').blueberry({hoverpause: true});
});

Now the image slider will start up showing images (and YouTube video).

Next comes dropping in the YouTube API, plus adding in the callback controls. The following snippet of JS code contains all of the code needed to start and stop slider when video is played and stopped by user. I'll explain it in the following sections.


1. The first closure is to load the youtube js API script. 

2. onPlayerStateChange is a function that is called each time the player changes state, it is passed an event object with what type of change occurred see the details in the YouTube API Docs.  

2a. This code will pause the slider when the video is playing (when event type is PLAYING). 

2b. When data event is type is PAUSED or ENDED restart slider. The Blueberry slider's code will restart the timeout interval at start and stop so it won't necessarily change right away. I could see expanding this code to only start when the video was ended in our case it wasn't required.

3. Create new API object and save player to global object (this could be done a bit cleaner by storing in a global object or something else - exercise for the reader :)

Once I waded through the various APIs, browser cross domain restrictions and code patches. The end solution wasn't too bad. The above YouTube API code could be used with any slider or carousel.

__END__

No comments:

Post a Comment