Tuesday, December 13, 2011

Learning oEmbed: Convert Links Into Embedded Content

In this tutorial I want to illustrate how to use oEmbed API to display embedded content (such as Flickr photos, YouTube or Vimeo videos) in your website. What’s oEmbed? oEmbed is a format for allowing an embedded representation of a URL on third party sites (YouTube, Flickr, Vimeo, Viddler, …).
In this tutorial I want to illustrate how to use oEmbed API to display embedded content (such as Flickr photos, YouTube or Vimeo videos) in your website.
What’s oEmbed? oEmbed is a format for allowing an embedded representation of a URL on third party sites (YouTube, Flickr, Vimeo, Viddler, …).

Where is oEmbed used?

Facebook probably has one of the most popular implementation of oEmbed. For example, when you copy a link from YouTube into your status bar, Facebook converts this link into an embedded movie.

How you can implement this feature? It’s really simple using jQuery oEmbed an easy to use jQuery plugin that helps you convert links into embedded content. Take a look at the live example below.

Live Example

Copy the following link into the input field above: http://www.youtube.com/watch?v=d6PDlMggROA
When your mouse loses the focus on the input field the YouTube movie will be embedded below. You can also use Vimeo, Viddler, Flickr links.

Source Code

First of all you have to download the jQuery oEmbed Plugin. Then you have to include on the tag of the page a link to jQuery and jQuery.oEmbed:

In your HTML page, you have to add an input field and div layer (into which your links will be embedded):

Now add this simple JavaScript function immediately after the body tag:
In this tutorial I used the blur() event but you can customize the code as you prefer (for example when an user submits the form). For the full reference guide to jQuery Events I suggest you to take a look at the jQuery official documentation.

Using Animation

If you want to implement the animation I used in this tutorial (the input field disappears with a fade-out effect after submitting a link) you have to change the HTML code in this way (wrap the input field with
...
):

and the JavaScript function in this way (add $("#oembedcont").fadeOut(1000);):
You can download the source code of this tutorial and reuse it on your web projects.

1 comment: