Changing iframe (Youtube and Vimeo) Video Size from Post to Home Page

Twitter0
Google+0
LinkedIn0
Facebook0

So, I ran into a dilemma. On my posts page, I had a youtube video. The dimensions were 580px by 320px. It was a nice widescreen view of the video. But, I had that same video pulling from the post back to my blog home page. The problem: the video was the same size.

I know, I could have taken a screen capture of the video, created a “a href” to the real post, and the problem would have been solved. But I wanted the user to be able to view the video as a thumbnail on the homepage. If they wanted to, they could go to the post, but if they wanted to watch a smaller video on the home page, then so be it.

The solution: a little jQuery. I needed a script that would reduce the video size from 580px by 320px to something a little smaller, a thumbnail size – 318px by 400px.

jQuery(document).ready(function($) {
$(function() {

var $allVideos = $("iframe[src^='http://player.vimeo.com'], iframe[src^='http://www.youtube.com'], object, embed"),
$fluidEl = $("p");

$allVideos.each(function() {

  $(this)
    // jQuery .data does not work on object/embed elements
    .attr('data-aspectRatio', this.height / this.width)
    .removeAttr('height')
    .removeAttr('width');
});

$(window).resize(function() {

  var newWidth = $fluidEl.width();
  $allVideos.each(function() {

    var $el = $(this);
    $el
        .width(318)
        .height(400 * $el.attr('data-aspectRatio'));

  });

}).resize();

});
});

This jQuery solutions strips the old dimensions and adds the new dimensions I was looking for.

Last hurdle: this script can’t load on every page. If it does, it will reduce the size of every video, including the widescreen video on the posts page.

Solution: only load the script on the page needed, or use WordPress conditional tags: is_home() || is_front() and the list could go on.

To see the example in action: Taste The Movement // The site is just getting started.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>