-
Notifications
You must be signed in to change notification settings - Fork 427
home
This is a jQuery component that let you play a Youtube® movie as background of your page or of an element of your page.
Available also as WordPress® component:
go to the WordPress® component page
- The plugin works only if used under a web server. It doesn’t work if you run the HTML page as file (file://…).
If you want to run it locally on your computer you need a web server installed (for ex: MAMP for Mac, XAMP for Windows, LAMP for linux) and reach the file from http://localhost… or whatever you mapped in the Host file as localhost.
- The plugin doesn’t work with jquery.slim.js as it requires methods that have been removed from the slim version of jQuery.
<link href="css/jquery.mb.YTPlayer.min.css" media="all" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="inc/jquery.mb.YTPlayer.js"></script>
jQuery(function(){
jQuery("#[playerID]").YTPlayer();
});
<div id="bgndVideo" class="player" data-property="{videoURL:'http://youtu.be/BsekcY04xvQ',containment:'body',autoPlay:true, mute:true, startAt:0, opacity:1}">My video</div>
data-property is an attribute of the TAG where you can pass the options of the player as an Object. Any of the below parameters can also be passed as option within the initialize function. The one defined as attribute of the TAG wins.
- mute: true (boolean) mute the audio;
- showControls: true (boolean) show or hide the player controls;
- useOnMobile: true (boolean) Define if the player should render on mobile devices.
- mobileFallbackImage: absolute/path/to/image (string) The path to the fallback image in case of background video on mobile devices and the “useOnMobile” option is set to false;
- coverImage: absolute/path/to/image (string) The path to the image used as background for the player if autoplay is set to false; if not set the player will show the first frame;
- ratio: ‘4/3’, ‘16/9’ or ‘auto’ (string) to set the aspect ratio of the movie; if ‘auto’ the aspect ratio will be retreived form the getDataFromFeed method.
-
quality: ‘default’ or ‘small’, ‘medium’, ‘large’, ‘hd720’, ‘hd1080’, ‘highres’.
The quality parameter has been deprecated on the YT API and never more used. YouTube adjusts the quality of your video stream based on your viewing conditions. - opacity: 0 to 1 (number) define the opacity of the video.
- containment: (string) the CSS selector of the DOM element where you want the video background; if not specified it takes the “body”; if set to “self” the player will be instanced on that element.
- optimizeDisplay: true (boolean) will fit the video size into the window size optimizing the view.
- loop: false (boolean) or a number rapresenting how many times the video should loops once ended.
- vol: 1 to 100 (number) set the volume level of the video.
- startAt: 20 (number) Set the seconds the video should start at.
- stopAt: 20 (number) Set the seconds the video should stop at. If 0 is ignored.
- remember_last_time: true (boolean) if true living the page and getting back the video will start where it was left.
- autoPlay: true (boolean) or false play the video once ready; with the latest vendor policy the autoplay works only if the mute option is set to true otherwise the video will start with the first click/touch user interaction with the page.
- showYTLogo: true (boolean) Show or hide the YT logo and the link to the original video URL.
- addRaster: false (boolean) Show or hide a raster image over the video.
- mask: ‘path/to/mask’ or object {0:‘path/to/mask1’, 20:‘path/to/mask2’, …} or false. From version 3.0. Add a mask to the player or a map of masks for each time specified.
- realfullscreen: true (boolean) activate the new HTML5 full screen behavior.
- stopMovieOnBlur: true (boolean) activate the pause behavior when the window loose focus.
- playOnlyIfVisible: false (boolean) activate the pause behavior when the player is out of screen.
- gaTrack: true (boolean) activate the Google Analytics event tracker for that player.
- anchor: ‘center,center’ (string) From version 3.0.3. Define how the video will behave once the window is resized; possible value are: ‘top,bottom,left,right,center’; it accept a pair of value comma separated (ex: ‘top,right’ or ‘bottom,left’).
- showAnnotations: false (boolean) Define if the player should or not show annotations.
- cc_load_policy: false (boolean) Define if the player should or not show subtitles.
- abundance: 0.2 (float) define the percentage of the size to add as abundance.
- useNoCookie: true (bool) use https://www.youtube-nocookie.com host to serve the video.
- onReady: (function) You can pass a function that will be fired once the player is ready; it will pass the YTPlayer object as parameter.
- onError: (function) You can pass a function that will be fired if there’s an error loading the video; it will pass the YTPlayer object and the error as parameter.
To initialize a YTPlayer as simple player:
<div id="P1" class="player"
data-property="{videoURL:'http://youtu.be/l_tHTmd5pgk',containment:'self',startAt:50,mute:false,autoPlay:false,loop:false,opacity:.8}">
</div>
To initialize a YTPlayer as background:
<div id="bgndVideo" class="player"
data-property="{videoURL:'http://youtu.be/BsekcY04xvQ',containment:'body',autoPlay:true, mute:true, startAt:0, opacity:1}"></div>
To initialize a YTPlayer as element background (from v. 1.2.1):
<div id="P1" class="player"
data-property="{videoURL:'http://youtu.be/l_tHTmd5pgk',containment:'#ElementID',startAt:0,mute:false,autoPlay:false,loop:false,opacity:1}">
</div>
What you can pass to the “videoURL” parameter:
To retrieve the video from YouTube you can use any of the following string:
- The URL of the page containing the video
videoURL: ‘https://www.youtube.com/watch?v=V2rifmjZuKQ’. - The short URL available from the YouTube share panel
videoURL: ‘http://youtu.be/V2rifmjZuKQ’. - The video ID
videoURL: ‘V2rifmjZuKQ’.
jQuery.fn.YTPlaylist(videos, shuffle, callback)
- Define an array of objects containing the properties for each video:
let videos = [
{videoURL:"VuaJAgx0x_4",containment:'body',autoPlay:true, mute:false, startAt:0,opacity:1, loop:false, ratio:"4/3", addRaster:true},
{videoURL: "3ovA7zeviRo",containment:'body',autoPlay:true, mute:true, startAt:0,opacity:1, loop:false, ratio:"4/3", addRaster:false},
{videoURL: "u9k1FaMIYTs",containment:'body',autoPlay:true, mute:false, startAt:0,opacity:1, loop:false, ratio:"4/3", addRaster:true}
];
- Initialize the player using the “jQuery.fn.YTPlaylist(videos, shuffle, callback)” method:
jQuery("#[playerID]").YTPlaylist(Array, boolean, function);
This method accepts 3 parameters:
- videos: (array) the array of objects describing each video.
- shuffle: (boolean) setting this to true you can have a random sequence of videos.
-
callback: (function) A callback function fired on each video change. it accepts the actual “video” as parameter. The “video” element passed to the function contains all the information retrieved using the Youtube API and stored in the videoData (video.videoData).
Example:
jQuery("#myPlayerID").YTPlaylist(videos, false, function(video){ jQuery("#videoID").html(video.videoData.id); jQuery("#videoTitle").html(video.videoData.title); jQuery("#videoDesc").html(video.videoData.description); });
Check the examples here
jQuery.fn.YTPChangeMovie(opt)
This method let you change the video of the specified player.
It accepts an Object as parameter containing all the data-property (see above) you need for the video; the only required is the videoURL parameter that can contain either the complete URL or the short URL provided by Youtube or the video ID.
For example:
<button onclick="jQuery('#[playerID]').YTPChangeMovie({videoURL:'http://youtu.be/3ovA7zeviRo',ratio:'4/3'})"> Dan Graham - Body Press, 1972 </button>
jQuery.fn.YTPPlay()
Let you play the video.
For example:
<button onclick="jQuery('#[playerID]').YTPPlay()">play</button>
jQuery.fn.YTPPause()
Let you pause the video.
For example:
<button onclick="jQuery('#[playerID]').YTPPause()">pause</button>
jQuery.fn.YTPStop()
Let you stop the video.
For example:
<button onclick="jQuery('#[playerID]').YTPStop()">stop</button>
jQuery.fn.YTPSeekTo(val)
Let you seek the video to a specific second.
For example:
<button onclick="jQuery('#[playerID]').YTPSeekTo(20)">seek to 20 sec.</button>
jQuery.fn.YTPGetPlaybackRate()
Let you get the actual video speed (playback rate).
For example:
<button onclick="jQuery('#[playerID]').YTPGetPlaybackRate()">Get playback rate</button>
jQuery.fn.YTPSetPlaybackRate(val)
Let you suggest the video speed (playback rate).
Possible value: 0.25, 0.5, 1, 1.5 and 2.
For example:
<button onclick="jQuery('#[playerID]').YTPSetPlaybackRate(0.25)">Set playback rate</button>
jQuery.fn.YTPFullscreen()
Let you switch video from background to front.
For example:
<button onclick="jQuery('#[playerID]').YTPFullscreen()">bring to front / send to back</button>
jQuery.fn.YTPSetVolume(val)
Let you change the video volume.
For example:
<button onclick="jQuery('#[playerID]').YTPSetVolume(20)">change volume</button>
jQuery.fn.YTPMute()
Let you mute the audio.
For example:
<button onclick="jQuery('#[playerID]').YTPMute()">mute</button>
jQuery.fn.YTPUnmute()
Let you unmute the audio.
For example:
<button onclick="jQuery('#[playerID]').YTPUnmute()">unmute</button>
jQuery.fn.YTPToggleVolume()
Let you switch from mute to unmute.
For example:
<button onclick="jQuery('#[playerID]').YTPToggleVolume()">unmute/unmute</button>
jQuery.fn.YTPGetPlayer()
Let you retrieve the original player returned by the YouTube API. You can then apply all the methods available on the API itself.
For example:
<button onclick="alert(jQuery('#[playerID]').YTPGetPlayer().getPlayerState())">get state</button>
jQuery.fn.YTPGetVideoData()
Returns the info data of the current video as JSON.
This method works only if the API key has been passed as option.
For example:
<button onclick="console.log(jQuery('#[playerID]').YTPGetVideoData())">video info</button>
jQuery.fn.YTPPlayNext()
Available only if you are playing a video list; go to the next video in the playlist.
For example:
<button onclick="jQuery('#[playerID]').YTPPlayNext()">play next</button>
jQuery.fn.YTPPlayPrev()
Available only if you are playing a video list; go to the previous video in the playlist.
For example:
<button onclick="jQuery('#[playerID]').YTPPlayPrev()">play previous</button>
jQuery.fn.YTPPlayIndex(idx)
Available only if you are playing a video list; go to a specific video in the playlist based on the index.
For example:
<button onclick="jQuery('#[playerID]').YTPPlayIndex(2)">play the second video in the list</button>
jQuery.fn.YTPGetTime()
Return the actual video time.
For example:
<button onclick="alert(jQuery('#[playerID]').YTPGetTime())">Get time</button>
jQuery.fn.YTPGetTotalTime()
Return the total video time.
For example:
<button onclick="alert(jQuery('#[playerID]').YTPGetTotalTime())">Get total time</button>
jQuery.fn.YTPGetAnchor()
Return the actual anchor point for the video.
For example:
<button onclick="alert(jQuery('#[playerID]').YTPGetAnchor())">Get anchor</button>
jQuery.fn.YTPSetAnchor(posX,posY)
Define how the video will behave once the window is resized; possible value are: ‘top,bottom,left,right,center’; it accept a pair of value comma separated (ex: ‘top,right’ or ‘bottom,left’)
For example:
<button onclick="jQuery('#[playerID]').YTPSetAnchor('center,center')">Set anchor</button>
Check the examples here
From version 2.8.5 you can apply CSS filters to the video (Except for IE that will not render CSS filters).
The available filters are:
- grayscale : 1-100,
- hue_rotate: 1-360,
- invert : 1-100,
- opacity : 1-100,
- saturate : 1-400,
- sepia : 1-100,
- brightness: 1-400,
- contrast : 1-400,
- blur : 1-100
Below you can find the list of available methods to manage filters; all those methods can be called after the YTPlayer has been initialized.
jQuery.fn.YTPApplyFilter(filter, value)
Apply a CSS filter to the player; accept the name of the filter and the value.
For example:
<button onclick="jQuery('#[playerID]').YTPApplyFilter('sepia', 50)">apply sepia effect</button>
jQuery.fn.YTPApplyFilters(filters)
Apply multiple CSS filters to the player; accept an object representing the list of filters to be applied as key: value.
For example:
let filters = {
sepia: 50,
hue_rotate : 220
}
jQuery('#[playerID]').YTPApplyFilters(filters)
jQuery.fn.YTPtoggleFilter(filter, value)
Toggles the filter from the passed value to 0 and vice-versa; accept the name of the filter and the value.
For example:
<button onclick="jQuery('#bgndVideo').YTPtoggleFilter('sepia', 50)">toggle sepia effect</button>
jQuery.fn.YTPToggleFilters(callback)
Toggles all the filters; accept a callback function.
For example:
<button onclick="jQuery('#[playerID]').YTPToggleFilters(function(val){alert('filters are enabled: ' + val)})">toggle all filters</button>
jQuery.fn.YTPRemoveFilter(filter, callback)
Removes the specified filter; accept the name of the filter and a callback function.
For example:
<button onclick="jQuery('#[playerID]').YTPRemoveFilter('sepia', function(filter){alert(filter)})">remove sepia effect</button>
jQuery.fn.YTPDisableFilters()
Disables all the appied filters.
For example:
<button onclick="jQuery('#[playerID]').YTPDisableFilters()">disable all filters</button>
jQuery.fn.YTPEnableFilters()
Enables all the appied filters.
For example:
<button onclick="jQuery('#[playerID]').YTPEnableFilters()">enable all filters</button>
You can also apply filters from the beginning invoking the method on the “onready” function as follow:
myPlayer = jQuery('#[playerID]').YTPlayer( {
onReady: function( player ) {
let filters = {
sepia: 50,
hue_rotate : 220
}
myPlayer.YTPApplyFilters(filters)
}
});
Check the examples here
From version 3.0 you can apply a mask to the video. A mask is a png file that will overlay the video.
Below you can find the list of available methods to manage mask; all those methods can be called after the YTPlayer has been initialized.
jQuery.fn.YTPAddMask(“path/to/mask”)
Add a mask to the target video player. If you call the YTPAddMask method while a mask has been already applied the previous mask will be replaced.
For example:
<button onclick="jQuery('#[playerID]').YTPAddMask('assets/mask-1.png')">Add Mask</button>
jQuery.fn.YTPRemoveMask()
Remove the previously applied mask from the target video player.
For example:
<button onclick="jQuery('#[playerID]').YTPRemoveMask()">Remove Mask</button>
jQuery.fn.YTPToggleMask()
toggle actual mask on and off.
For example:
<button onclick="jQuery('#[playerID]').YTPToggleMask()">Toggle Mask</button>
You can also use those methods within the “YTPTime” event trigger to display a specific mask at a specific time during the video play.
For example:
let myPlayer = jQuery('#[playerID]').YTPlayer();
myPlayer.on("YTPTime", function (e) {
let currentTime = e.time;
switch (currentTime) {
case 1:
myPlayer.YTPAddMask('assets/mask-2.png');
break;
case 10:
myPlayer.YTPAddMask('assets/mask-1.png');
break;
case 15:
myPlayer.YTPRemoveMask();
break;
case 20:
myPlayer.YTPAddMask('assets/mask-4.png' );
break;
}
});
You can also define the mask via the options:
//Single mask
let myPlayer = jQuery("#[playerID]").YTPlayer({mask:'assets/mask-1.png'});
Or:
//Multiple masks time:mask
let myPlayer = jQuery("#[playerID]").YTPlayer({
mask:{
0:'assets/mask-1.png', // at the beginning
5:'assets/mask-4.png',
25:'assets/mask-1.png',
30: false,
50:'assets/mask-4.png'
}
});
Check the examples here
The player triggers a specific event for each state:
- YTPUnstarted: Before the video start playing (time is passed on the event object)
- YTPBuffering: When the video is buffering (time is passed on the event object)
- YTPReady: When the video is ready to start playing
- YTPStart: When the video starts playing (time is passed on the event object)
- YTPPlay: Each time the video change from paused to play.
- YTPPause: When the video pause (time is passed on the event object)
- YTPEnd: When the video ends; you can retrieve the time on the event object.
- YTPFullScreenStart: When the video goes full-screen modality
- YTPFullScreenEnd: When video exit full-screen modality
- YTPMuted: When the video is muted
- YTPUnmuted: When the video is unmuted
- YTPTime: Fired every second (time is passed on the event object: e.time)
- YTPData: Fired on feed data retrieved (prop are passed on the event object: e.prop)
You can use these events to fire functions on a specific event as follow:
jQuery('#[playerID]').on("YTPEnd",function(e){
let currentTime = e.time;
//your code goes here
});
jQuery('#[playerID]').on("YTPTime",function(e){
let currentTime = e.time;
if(currentTime == 20) //if the player is at the 20th second
//do something
});
This event let you get informations on the video you are playing. To activate this option you need a Youtube API key that you can pass to the component as an option just before initializing it:
jQuery.mbYTPlayer.apiKey = "xxxxxx_xxxxxxxxxxxxxxxxxxxx";
let myVideo = jQuery('#[playerID]').YTPlayer();
myVideo.on("YTPData", function(e){
console.debug("******************************");
console.debug(e.prop.title);
console.debug(e.prop.description.replace(/\n/g, "<br/>"));
console.debug("******************************");
});
You can also refer to the data directly from the YTPlayer instance once the data are available:
jQuery.mbYTPlayer.apiKey = "xxxxxx_xxxxxxxxxxxxxxxxxxxx";
let myPlayer = jQuery(".player").YTPlayer();
jQuery("#myButton").on("click", function(){
if(myPlayer && myPlayer.YTPGetVideoData()){
jQuery("#myInfobox").html(myPlayer.YTPGetVideoData().description);
}
})
Below the available video properties:
video.videoData properties:
- videoData.id
- videoData.channelTitle
- videoData.title
- videoData.description
- videoData.thumb_max
- videoData.thumb_high
- videoData.thumb_medium
how to obtain a Youtube API key
From the 3.0 release the player will be rendered also on mobile devices with the unique difference that it needs a first touch on screen to start. You can anyway prevent the rendering on mobile by setting the “useOnMobile” option to false either on the video placeholder element or initializing the player:
let myPlayer = jQuery(".player").YTPlayer({useOnMobile:false});
Or:
<div id="bgndVideo" class="player" data-property="{videoURL:'http://youtu.be/BsekcY04xvQ',containment:'body', useOnMobile:false, autoPlay:true, mute:true, startAt:0, opacity:1}"></div>
If you are tracking your site with Google Analytics each player included into a page will generate a ga_event to get statistics for that video under the “Behavior > Events” Google Analytics tab.
If you don’t want ADs on your background video and you are the owner of it you can disable advertisings on your Youtube channel as explained here.