Blog

Thoughts from my daily grind

Responsive YouTube Embed - JS Approach

Posted by Ziyan Junaideen |Published: 25 November 2021 |Category: Ruby on Rails
Default Upload |

A Google Webmaster Tools alert regarding mobile usability got my interest this morning. The alert was about a recent blog post that had an embedded YouTube video. I have personally experienced this matter reading blog posts with embedded YouTube videos and thought of finding a solution.

YouTube video embed code has a static width and height making it not responsive. I found Responsive YouTube Video Embeds. It looks good, but I didn't try it.

I preferred a solution that just works and wrote a CoffeeScript class.

# app/assets/javascripts/utilities/youtube_rsize.coffee
class @YouTubeResize
  @init: ->
    for element in $('iframe')
      iframe = $(element)
      return unless iframe.attr('src').includes("youtube")

      newWidth = iframe.parent().width()
      newHeight = iframe.height() * newWidth / iframe.width()

      return if iframe.width() < iframe.parent().width()

      iframe.attr('height', newHeight)
      iframe.attr('width', newWidth)

      # TODO: Handle resize event

In the application.coffee:

#= ...
#= require utilities/youtube_resize

setup = ->
  YouTubeResize.init()

$(document).on 'turbolinks:load', -> setup()

I deployed the updates and inspected the page. I was worried the JS solution will not work but it did.

Tags
About the Author

Ziyan Junaideen -

Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.

Comments