Skip to content

Instantly share code, notes, and snippets.

@cowgp
Created January 5, 2012 19:36
Show Gist options
  • Select an option

  • Save cowgp/1566821 to your computer and use it in GitHub Desktop.

Select an option

Save cowgp/1566821 to your computer and use it in GitHub Desktop.
Uncorked Javacript Video Playback
/*
This plugin is designed to ease creation of videos, whether they are provided
or Youtube links. The plugin requires the FancyBox extension be present.
First, the createVid() function needs to be called. It can be passed vars and events.
If you would rather pass these separately (in case you want to run createVid() on all
your videos but have them have different events/vars), this is possible by running
addVars(vars) after createVid() has been run.
To add a YouTube video, call .createVid() on an element with an attribute called
vidType="yt". The element must have a src attribute that equals the video's ID.
YouTube videos can have event handlers attached, formatted as per the YouTube API
(http://code.google.com/apis/youtube/js_api_reference.html#Events), passed to a
function called addEvents. Player variables can be passed, again formatted as per
the YouTube API (http://code.google.com/apis/youtube/player_parameters.html), to
the function called addYTVars.
To add an HTML5 video, call createVid() on an element with an attribute called
vidType="html5vid". The HTML5 video source must be present in the element.
The element must have a "src" attribute which containst the name of the video.
The element must also have a "ext" attribute which contains a comma-delimited list
of extensions of the videos presented. Ex. ext="mp4,ogg". Events can be
attached to HTML5 videos by calling addEvents(events), where events is a dictionary
matching the event calls (listed here:
http://www.w3.org/TR/html5/video.html#mediaevents) to a function call, e.g.
'myFunction()'.
To add a link to an HTML5 video, call createVid() on an element with an attribute
called vidType="anch" (if the element is an anchor, that is the anchor that will be
used. A new one will not be made). The anchor does 1 of 2 things dependent on whether
or not the device is mobile. If it is mobile, it creates a small 1x1 div at the bottom
of the page called VideoPlayback. When the user clicks the anchor, that video is played.
If the webpage is displayed on a non-mobile browser, the video is played in a
FancyBox display. The element must have a "src" attribute which containst the name
of the video. The element must also have a "ext" attribute which contains a
comma-delimited list of extensions of the videos presented. Ex. ext="mp4,ogg". The
text that will be used for the anchor should be placed between the two element tags used.
Example:
<div id="anchVideo" vidType="anch" src="sintelClip.mp4" >This is the anchor</div>
It's possible that you'll want to have an event occur when you click a link (like
click tracking). In this case, you can call ucVideoAnchClicked(button), where button
is a reference to whatever anchor was clicked. For instance, you could have:
$('.myAnchor').click(function() {
countClick();
ucVideoAnchClicked($(this));
}
and the video will launch as expected. It is worth noting that it would be a good
idea to cancel the default action of this item being clicked.
*/
var addYoutubeAPI = true;
var vidHeight = new Array();
var vidWidth= new Array();
var vtid = new Array();
var elid = new Array();
var mEvents = new Array();
var mVars = new Array();
var playerArray = new Array();
var contentArray = new Array();
//var isMobile = DetectTierIphone();
//var isIOS = DetectIos();
if(addYoutubeAPI){
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
(function( $ ) {
var videoObjectDisplayed = false;
var playerTarget;
var container;
_onPlayerReady = function(event) {
event.target.playVideo();
}
_onPlayerStateChange = function (event) {
//alert(event.data);
if (event.data == YT.PlayerState.ENDED) {
container.empty();
videoObjectDisplayed = false;
}
}
$.fn.createYT = function(options) {
if (!$(this).length) {
return this;
}
container = $(this);
videoObjectDisplayed = false;
$(this)
.data('ucVideo', $.extend({}, options))
.data('poster_content',$(this).html())
.unbind('click')
.bind('click', function(e) {
e.preventDefault();
if(videoObjectDisplayed){
return;
}
videoObjectDisplayed = true;
$(this).blur();
var params = $(this).data('ucVideo');
$(this).empty();
player = new YT.Player($(this).attr("id"), {
width: params.width,
height: params.height,
videoId: params.videoId,
playerVars: params.playerVars,
events: {
'onReady': _onPlayerReady,
'onStateChange': _onPlayerStateChange
}
});
return;
});
return this;
};
$.fn.createHtml5 = function(options) {
if (!$(this).length) {
return this;
}
container = $(this);
videoObjectDisplayed = false;
$(this)
.data('ucVideo', $.extend({}, options))
.data('poster_content',$(this).html())
.unbind('click')
.bind('click', function(e) {
e.preventDefault();
if(videoObjectDisplayed){
return;
}
videoObjectDisplayed = true;
$(this).blur();
var params = $(this).data('ucVideo');
var vid = "<video id='" + $(this).attr("id") + "_vid' width='"+params.width+"' height='"+params.height+"' preload='none'>";
vid += "<source src='" + params.mp4 + "' />";
vid += "</video>";
$(this).append(vid);
var vidId = $(this).attr("id") + "_vid";
var v = document.getElementById(vidId);
v.play();
//android needs a delay, but normal setTimeout does not appear to trigger so using setInterval
var _t=setInterval(function(){
//alert("timeout triggered");
var v = document.getElementById(vidId);
v.play();
clearInterval(_t)
}, 100);
$("#"+vidId).bind('ended',function(){
container.empty();
videoObjectDisplayed = false;
});
return;
});
return this;
};
$.fn.createHtml5AutoPlay = function(options) {
if (!$(this).length) {
return this;
}
container = $(this);
videoObjectDisplayed = false;
$(this).data('ucVideo', $.extend({}, options));
if(videoObjectDisplayed){
return;
}
videoObjectDisplayed = true;
$(this).blur();
var params = $(this).data('ucVideo');
var vid = "<video id='" + $(this).attr("id") + "_vid' width='"+params.width+"' height='"+params.height+"' preload='none'>";
vid += "<source src='" + params.mp4 + "' />";
vid += "</video>";
$(this).append(vid);
var vidId = $(this).attr("id") + "_vid";
var v = document.getElementById(vidId);
v.play();
//android needs a delay, but normal setTimeout does not appear to trigger so using setInterval
var _t=setInterval(function(){
//alert("timeout triggered");
var v = document.getElementById(vidId);
v.play();
clearInterval(_t)
}, 100);
$("#"+vidId).bind('ended',function(){
container.empty();
videoObjectDisplayed = false;
});
return this;
};
})( jQuery );
(function( $ ) {
$.fn.createVid = function(vars, events ) {
//$('body').append('<div id="loadingSpinner" class="spinner"><img src="spinner.gif" alt="loading..." /></div>');
this.each(function() {
var $this = $(this);
mVars[$this.attr("id")] = vars;
mEvents[$this.attr("id")] = events;
if($this.attr("vidType") == "yt") {
vtid.push($this.attr("src"));
vidHeight.push($this.attr("height"));
vidWidth.push($this.attr("width"));
elid.push($this.attr("id"));
}
if($this.attr("vidType") == "anch") {
$('body').append('<div id="videoPlayback"></div>');
if(!isMobile) {
if($this.is("div")) {
var anchStr = "<a href='.' alt='" + $this.attr('alt') + "' id='" + $this.attr("id") + "_link' >";
anchStr += $this.html() + "</a>";
$this.html(anchStr);
}
var contentStr = "<video id='" + $(this).attr("id") + "_vid'";
if(vars != null) {
var width = vars["width"] == null ? 320 : vars["width"];
var height = vars["height"] == null ? 240 : vars["height"];
for(key in vars) {
contentStr += " " + key + "=" + vars[key];
}
} else {
contentStr += "height=240 width=320 controls=controls";
}
contentStr += ">";
var extArray = $this.attr("ext").split(',');
for(ext in extArray) {
contentStr += "<source src='" + $this.attr("src") + "." + extArray[ext] + "' />";
}
contentStr += "</video>";
contentArray[$this.attr("id")] = contentStr;
var vidId = "#" + $(this).attr("id") + "_vid";
$(this).fancybox({'content': contentStr});
}
}
if($this.attr("vidType") == "html5vid") {
var htmlStr = "<video width='" + $this.attr("width") + "' id='" + $this.attr("id") + "_vid' height='" + $this.attr("height") + "' controls onclick='this.play()'>";
var extArray = $this.attr("ext").split(',');
for(ext in extArray){
htmlStr += "<source src='" + $this.attr("src") + "." + extArray[ext] + "' />";
}
htmlStr += "</video>";
//htmlStr += "Your browser doesn't support HTML5</video>";
$this.html(htmlStr);
var tmpId = "#" + $this.attr("id") + "_vid";
for(var k in vars) {
$(tmpId).attr(k,vars[k]);
}
for(var k in events) {
$(tmpId).attr(k,events[k]);
}
}
});
onYouTubePlayerAPIReady();
};
$.fn.addVideo = function(vid) {
return this.each(function() {
var $this = $(this);
var vidId = "#" + $this.attr("id") + "_vid";
var inHtml = $(vidId).html();
$(vidId).html(inHtml + "<source src=" + vid + "/>");
});
};
$.fn.addFBVars = function( vars ) {
return this.each(function() {
var $this = $(this);
if(!isMobile) {
vars["content"] = contentArray[$this.attr("id")];
$this.fancybox(vars);
}
});
};
$.fn.addVars = function( vars ) {
return this.each(function() {
var $this = $(this);
if($this.attr("vidType") == "html5vid") {
var tmpId = "#" + $this.attr("id") + "_vid";
for(var k in vars) {
$(tmpId).attr(k,vars[k]);
}
}
if($this.attr("vidType") == "anch") {
if(!isMobile) {
var width = vars["width"] == null ? 320 : vars["width"];
var height = vars["height"] == null ? 240 : vars["height"];
var contentStr = "<video id='" + $(this).attr("id") + "_vid'";
for(key in vars) {
contentStr += " " + key + "=" + vars[key];
}
contentStr += ">";
var extArray = $this.attr("ext").split(',');
for(ext in extArray) {
contentStr += "<source src='" + $this.attr("src") + "." + extArray[ext] + "' />";
}
contentStr += "</video>";
contentArray[$(this).attr("id")] = contentStr;
vars["content"] = contentStr;
$this.fancybox(vars);
}
}
});
};
$.fn.addEvents = function( events ) {
return this.each(function() {
var $this = $(this);
if($this.attr("vidType") == "html5vid") {
var tmpId = "#" + $this.attr("id") + "_vid";
for(var k in events) {
$(tmpId).attr(k,events[k]);
}
}
});
};
$.fn.togglePlay = function() {
return this.each(function() {
var $this = $(this);
var vidId = $this.attr("id");
if($this.attr("vidType") == "html5vid") {
$this = document.getElementById(vidId + '_vid');
if($this.paused) {
$this.play();
} else {
$this.pause();
}
} else {
playerArray[vidId].getPlayerState() == 1 ? playerArray[vidId].pauseVideo() : playerArray[vidId].playVideo();
}
});
};
$.fn.play = function() {
return this.each(function() {
var $this = $(this);
var vidId = $this.attr("id");
if($this.attr("vidType") == "html5vid") {
$this = document.getElementById(vidId + '_vid');
$this.play();
} else {
playerArray[vidId].playVideo();
}
});
};
$.fn.pause = function() {
return this.each(function() {
var $this = $(this);
var vidId = $this.attr("id");
if($this.attr("vidType") == "html5vid") {
$this = document.getElementById(vidId + '_vid');
$this.pause();
} else {
playerArray[vidId].pauseVideo();
}
});
};
})( jQuery );
function ucVideoAnchClicked(button) {
$('#videoPlayback').extend();
if(isMobile) {
if(isIOS) {
var vid = "<video id='" + button.attr("id") + "_vid' width='1' height='1' preload='none' onended='this.play();'>";
} else {
var vid = "<video id='" + button.attr("id") + "_vid' width='1' height='1' preload='none';'>";
}
var extArray = button.attr("ext").split(',');
for(ext in extArray) {
vid += "<source src='" + button.attr("src") + "." + extArray[ext] + "' >";
}
vid += "</video>";
$('#videoPlayback').append(vid);
var vidId = button.attr("id") + "_vid";
var v = document.getElementById(vidId);
v.play();
var _t = setInterval(function() {
var v = document.getElementById(vidId);
v.play();
clearInterval(_t);
},100);
} else {
}
}
$('.ucVideo').bind('vclick', function() {
if($(this).attr("vidType") == "anch") {
ucVideoAnchClicked($(this));
}
});
function onYouTubePlayerAPIReady() {
for(var i = 0; i < elid.length; i++) {
var player = new YT.Player(elid[i], {
height: vidHeight[i],
width: vidWidth[i],
videoId: vtid[i],
events: mEvents[elid[i]],
playerVars: mVars[elid[i]]
});
playerArray[elid[i]] = player;
}
};
function showSpinner(who) {
var loc = $("#" + who).offset();
$("#loadingSpinner").offset({top:loc.top, left:loc.left});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment