Replace or reset YouTube iframe embed when video ends (fix rel=0 with YouTube Player API)

Things we know:

  1. rel=0 no longer works as a YouTube parameter, so random “related videos” show up when a video completes
  2. having related videos that are not related to the video or from a different source is typically the worst
  3. there is a non-hack fix, so fix it

YouTube’s API Event Player Object:

YouTube’s API has an Events Player Object with an “onPlayerStateChange” method (a method is a named function that belongs to an object).

The onPlayerStateChange event fires every time player action happens, including buffering. The event mapping looks like this:

  • Buffering: 3
  • Cued: 5
  • Ended: 0
  • Paused: 1
  • Unstarted: -1

In your code (assuming your method parameter is named event), you can check event.data against the corresponding code like this:

screenshot events player example onPlayerStateChange event to swap out iframe on ENDED

At the time of writing (March 2020), the event.target parameters being swapped are as follows:

  • event.target.f — is the youtube api embedded iframe
  • event.target.l — is the initial display div (poster image and play button) that triggers the youtube api to call the corresponding video
screenshot if statement replacing youtube api iframe embed with original div

View It In Action:

View in use on my site here: https://crrollyson.com/yt-api.html

If you found this article helpful, pay it forward.

Visit my portfolio site here: https://crrollyson.com
Get our freelance design+development marketing support here: https://siderole.com

--

--

--

Amazing father, decent husband, marketing experience designer+developer advisor. Having a good time w/ good folks.

Love podcasts or audiobooks? Learn on the go with our new app.

Set up infrastructure in Hetzner Cloud using Terraform

This Video Game Started My Career

| Engineering News-Record

Reddit bot in Python to gain karma

Azure Cosmos DB

Create a new AI Platform Notebooks using Python

Reactive Event-Driven Systems and Recommended Practices

Chapter 2— Function Point Analysis: Project Management Course -AUG Unversity

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
CR Rollyson

CR Rollyson

Amazing father, decent husband, marketing experience designer+developer advisor. Having a good time w/ good folks.

More from Medium

Things to be Focussed While Developing an Effective App and Web:

The Awful Leisure Activity Of Evaluating CDN Vendors For Your WordPress Site

My Experience with Atlassian Collaboration tools

5 custom codes for every non-coder using Brooklyn Theme in Shopify

Brooklyn Theme Shopify Hero Section