Updated 11.25.2014

Step by Step Instructions for Displaying a Vimeo feed with jQuery

Prologue

A while back, I wrote a post on displaying a Vimeo feed using jQuery.

Recently, I had to do this for a client site. Knowing, I had written a blog post, I naturally, pulled up my blog post, so I could follow my own advice. (One of the good things about blogging = documenting your own process)

However, I quickly discovered, my code was outdated. None of it worked! Even the site that I referenced in my post, their code didn’t work! My Google Search returned my post as the top hit! — and any links after that were outdated too!

So, I wanted to update my content, using code that actually works (go figure).


The Actual Work

I found a code repository on GitHub that had everything I needed. So, download the code (direct link).

Vimeo Feed and jQuery Screenshot

You’ll see there are several examples for you to work from. No need to reinvent the wheel!

For the site I was working on, I neeed to display a featured video at the top with thumbnails beneath it. Within the simple-api folder, there’s a folder called gallery, then I grabbed the js-example.html file. It already has everything you need.

Displaying a Vimeo Feed - Finder

I copied the CSS out of the header, and placed it in my site’s CSS.

#thumbs { 
  height: 298px; 
  width: 300px; 
  border: 1px solid #E7E7DE; 
  padding: 0; 
  float: left;
  
    ul { 
      list-style-type: none; 
      margin: 0 10px 0; 
      padding: 0 0 10px 0;
      
      li { 
        height: 75px; 
      }
  }
}

.thumb { 
  border: 0; 
  float: left; 
  width: 100px; 
  height: 75px; 
  background: url(http://a.vimeocdn.com/thumbnails/defaults/default.75x100.jpg); 
    margin-right: 10px; 
}

#embed { 
  background-color: #E7E7DE; 
  height: 280px; 
  width: 504px; 
  float: left; 
  padding: 10px; 
}

#portrait { 
  float: left; 
  margin-right: 5px; 
  max-width: 100px; 
}
  
#stats { 
  clear: both; 
  margin-bottom: 20px; 
}

See the Pen 0f95ad9ca28dad9a3367d7a81dc6d55a by Amy Dutton (@ahaywood) on CodePen.

I also copied the javascript and pasted it in my site’s JS folder. (Don’t forget to make sure you’re using jQuery).

var apiEndpoint = 'http://vimeo.com/api/v2/';
var oEmbedEndpoint = 'http://vimeo.com/api/oembed.json'
var oEmbedCallback = 'switchVideo';
var videosCallback = 'setupGallery';
var vimeoUsername = 'brad';

// Get the user's videos
$(document).ready(function() {
  $.getScript(apiEndpoint + vimeoUsername + '/videos.json?callback=' + videosCallback);
});

function getVideo(url) {
	$.getScript(oEmbedEndpoint + '?url=' + url + '&width=504&height=280&callback=' + oEmbedCallback);
}

function setupGallery(videos) {

	// Set the user's thumbnail and the page title
	$('#stats').prepend('<img id="portrait" src="' + videos[0].user_portrait_medium + '" />');
	$('#stats h2').text(videos[0].user_name + "'s Videos");

	// Load the first video
	getVideo(videos[0].url);

	// Add the videos to the gallery
	for (var i = 0; i < videos.length; i++) {
		var html = '<li><a href="' + videos[i].url + '"><img src="' + videos[i].thumbnail_medium + '" class="thumb" />';
		html += '<p>' + videos[i].title + '</p></a></li>';
		$('#thumbs ul').append(html);
	}

	// Switch to the video when a thumbnail is clicked
	$('#thumbs a').click(function(event) {
		event.preventDefault();
		getVideo(this.href);
		return false;
	});

}

function switchVideo(video) {
	$('#embed').html(unescape(video.html));
}

See the Pen 0f95ad9ca28dad9a3367d7a81dc6d55a by Amy Dutton (@ahaywood) on CodePen.

Replace the vimeoUsername name with the vimeo user you’re trying to pull from.

Displaying a Vimeo Feed

Then, copy and paste the containers within the HTML, into yours. it’s important that you leave the id tags alone so that the JS can grab them…errr.. if you’re going to change them, change them within the JS file too. Also, make sure those tags don’t conflict with your existing DOM.

<div id="stats">
  <h2></h2>
	<div style="clear: both;"></div>
</div>
<div id="wrapper">
	<div id="embed"></div>
	<div id="thumbs">
		<ul></ul>
	</div>
</div>

See the Pen 0f95ad9ca28dad9a3367d7a81dc6d55a by Amy Dutton (@ahaywood) on CodePen.

You should be good to go! — Unless of course, you want to restyle some elements (which is what I did). But, this will at least get you pointed in the right direction.

See the Pen 0f95ad9ca28dad9a3367d7a81dc6d55a by Amy Dutton (@ahaywood) on CodePen.



Posted 11.25.2009

Updated 02.28.2015

Writing jQuery Plugins (Part 1)

The more I write code, the more I realize how repetitive it is. It’s more cost effective (and brain-thawing), if you can figure out ways to be reuse your code. A few weeks ago, I started trying to figure out how to write my own jQuery plugins. Granted, you can probably find an existing plugin for anything that catches your fancy, however, a lot of times, the footprints are larger than necessary to accommodate more people. Besides, I’ll usually find one effect and stick to it (personal preference), rendering most of the customization in the plugin useless. At this point, it becomes easier to write my own code.


EXISTING JQUERY PLUGIN TUTORIALS

Here are a few sites that I looked at to help me get a grasp on structure. As most things, some are better than others. The hard part is some people assume you know more or less, leaving you to put the pieces together. My goal, in this post, is to the heavy lifting for you.


First things First

I’m gonna assume that you’ve at least heard of jQuery. If not, the elevator pitch? It’s a framework for JavaScript. In my humble opinion, it’s far easier to understand and much easier to write than JavaScript. If you’re a web developer, it’s definitely something worth checking out. I’d start by visiting the jQuery site or I’ve listed a few books (yes, you read that correctly, books) at the bottom of this post.


Captain Obvious

The first thing you’ll need to do is download the jQuery library. This has to be included on your page before any jQuery code can be written.

<script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> 

Update February 28, 2015

One of the things I prefer to do is use Google’s CDN version of jQuery. Several reasons:

  • It prevents me from having to download the code and store it on my server.
  • If your user has visited another site that is using Google’s CDN version of jQuery, then their computer will cache the code on their computer. Then, when that same user visits your site, the code is already cached and it’s one less thing they will need to download to get your site to load.

Instead of using the above line, you can use this instead:

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Digging In

File Naming Structure

Your file should always be called jquery.your_plugin_name.js. Obviously, your_plugin_name will be unique to your plugin.


Documentation

Yes, documenting your code is a pain. However, I promise, when you come back to your code, months later, it more than pays off. The code that you say (and wish) you will never come back to will inevitably haunt you. (can you hear the agony of experience in my voice?) :-) Besides, plugins are meant to be reused.

At the top of my file, I list out the name of the plugin, the date that I wrote it, the author (me!), my url, requirements, and implementation.

/* ==================================================================
*
*    ROLLOVERS PLUGIN
* 
*    DATE:                 FEBRUARY 28, 2015
*    AUTHOR:             AMY HAYWOOD
*     URL:                 WWW.AMYHAYWOOD.COM
*
*    REQUIREMENTS:         jQuery
*                        Be sure to include the jQuery library before including this script
*     IMPLEMENTATION:
*        Within the $(document).ready(); all that you really need to include is:
*        |    $('.CLASS_NAME_FOR_ROLLOVER').rollover();
*        
*        Within your HTML, be sure to give the image, use the same classname that you used to call .rollover()
*        Within the rel attribute, include the path to the rollover image
*        |    
*
===================================================================== */

Code within your plugin

Basically, every plugin that you will write, will have the following code in it.


(function($) {
    $.fn.rollover = function(options){
        // DEFINE OPTIONS
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {

        });
    };
})(jQuery); 

Let’s take a step back…


A QUICK EXAMPLE :: ROLLOVERS

THE LOGIC

  • I want to have an image with the file path of the rollover in the rel attribute.
  • When the user rolls over the image, it is swapped out with the value provided in the rel attribute.
  • When the user rolls off the image, it is swapped back to the original image.

Easy enough?


IF I WAS WRITING THE CODE FOR 1 SITE

If I didn’t plan on using this code again, I would simply put the following code in the $(document).ready(); code in my header.


$(document).ready(function() {
    
    $('img[rel]').each(function() {
        var curImg = $(this);
        
        // GET THE VALUES
        var defaultImage = $(curImg).attr('src');
        var rolloverImage = $(curImg).attr('rel');
        
        // SET UP THE ROLLOVER BEHAVIOR
        $(curImg).hover(function() {
            $(curImg).attr('src', defaultImage);
        }, function() {
            $(curImg).attr('src', rolloverImage);
        });
    });
});

Too much too fast? No worries. I’ll break it down.

When you write jQuery code, most of it will appear within $(document).ready();. Basically, it waits until all the pieces on your web page have loaded and are available.

In this example, if we tried to find all the images before they had even loaded, it would return nothing!


$('img[rel]'.each(function() { 

This line of code looks for every image with a rel attribute. For EACH item, it will grab the current image src $(curImg).attr(‘src’) and save it as defaultImage. Then, it will grab the path for the rollover image $(curImg).attr(‘rel’) and save that as rolloverImage.

Lastly, it will set up the behavior. The hover function takes two parameters. The first, will determine what happens when you rollover the item and the second parameter will determine what happens when you roll off. In this case, it’s just a matter of setting the img src based on the defaultImage and rolloverImage.


MAKING THE CODE RESUABLE

Basically, we take the code that we would have made for 1 site and plug it into our jQuery plugin structure. The hardest part is just making sure we abstract everything (a.k.a. make it generic enough so that we can use it over and over).


(function($) {
    $.fn.rollover = function(options){
        // DEFINE OPTIONS
        var defaults = {};

        var settings = $.extend(defaults, options);

        return this.each(function() {
            var $element = $(this);
            var defaultImage = $element.attr('src');

            $element.hover(function() {
                $element.attr('src',  $element.attr('rel'));
            }, function() {
                $element.attr('src', defaultImage);
            });

        });
    };
})(jQuery); 

The only thing that I changed was I took out the code that was in the .each() function (from my 1 site code) and placed it within the this.each(function() { }); of the plugin. Now, when I call the plugin, it will run the loop on all the items I pass to it.

So, in the header of my HTML file, it will look like this:


<header>
    <title>JQUERY ROLLOVER TEST</title>
    
    <!-- LINK JAVASCRIPT FILES -->
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/jquery.rollovers.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function () {
            // INITIALIZE PLUGIN
            $('.CLASS_NAME_FOR_ROLLOVER').rollover(); 
        });
    </script>
</header> 

Now, for every item in the body that has a class name of .CLASS_NAME_FOR_ROLLOVER it will try and create a rollover.


Stay Tuned

This post would probably fit into the “assuming you know less” category. On Friday, I’ll take a more in depth look at plugins, demonstrating their extensibility (i.e. setting preferences). Just to whet your appetite, we’ll be building an image rotator where you can pass in the speed.

Download My Code

jquery.rollovers.js (kB)


CALL ME OLD FASHIONED

Call me old fashioned, but I still enjoy reading programming books. I know, ancient. I love my Kindle, but there is still something to be said for flipping pages, laying out multiple books, and cross-referencing. With that said, my favorite jQuery resources are books. That’s how I taught myself.


Learning jQuery
This is the book that I used to teach myself jQuery.


jQuery Reference
This book is also published by Pakt Publishing. This is the book that I go to for reference.


jQuery in Action
Yes, the cover looks a little hokey, but some of the content in the appendixes is worth the book’s weight in gold.