Vimeo Universal Player JS API example
A quick example of how to use interact with a Vimeo player using postMessage.
by beneverard
HTML
<iframe src="http://player.vimeo.com/video/27855315?api=1" width="400" height="225" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>
<div class="video-notes">
<article data-time="3">
1
</article>
<article data-time="11">
2
</article>
<article data-time="20">
3
</article>
</div>
CSS
.current-note {
background-color: blue;
color: white;
}
JavaScript
var f = $('iframe'),
url = f.attr('src').split('?')[0],
status = $('.status'),
video_notes = {};
$(document).ready(function() {
$('.video-notes article').each(function() {
video_notes[$(this).data('time')] = $(this);
});
});
// Listen for messages from the player
if (window.addEventListener){
window.addEventListener('message', onMessageReceived, false);
}
else {
window.attachEvent('onmessage', onMessageReceived, false);
}
// Handle messages received from the player
function onMessageReceived(e) {
var data = JSON.parse(e.data);
switch (data.event) {
case 'ready':
onReady();
break;
case 'playProgress':
onPlayProgress(data.data);
break;
}
}
// Helper function for sending a message to the player
function post(action, value) {
var data = { method: action };
if (value) {
data.value = value;
}
f[0].contentWindow.postMessage(JSON.stringify(data), url);
}
function onReady() {
status.text('ready');
post('addEventListener', 'playProgress');
}
function onPlayProgress(data) {
var seconds = Math.ceil(data.seconds),
$note_element;
$.each(video_notes, function(i, val) {
if ( seconds > i ) {
$note_element = val;
}
});
if ( $note_element !== undefined ) {
if ( ! $note_element.hasClass('current-note') ) {
$('.video-notes article').removeClass('current-note');
$note_element.addClass('current-note');
}
}
}