Fix Rel=0 YouTube iFrame Embed When Video Ends | YouTube Player API Code Copy

CR Rollyson
2 min readMar 19, 2020

--

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 | the youtube api embedded iframe
  • event.target.l | 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/videos.html

If you found this helpful, like > follow > share > comment.

CR Rollyson is a Digital User Experience & Web Manager for a S&P 500 Fintech company and is the COO of Side Role, a marketing team in Charlotte North Carolina partnering with In-house Teams & Agencies, Non-profits, and Start-Ups. Learn more about Side Role here.

--

--

CR Rollyson
CR Rollyson

Written by CR Rollyson

I lead initiatives to enhance customer engagement and digital strategy. 16+ years specializing in integrating emerging technologies to drive business growth.

No responses yet