Thumbnail

Adding class into parent from an iframe

Thumbnail

Feb Dao

|

I have faced an issue on a recent project. There is a media block which shows video from youtube. A class called `media--loaded` need to be added into parent of youtube iframe, this is how I did it by using javascript.

First, we need to create a function name onPlayerReady

window.onYouTubeIframeAPIReady = function () {
  const iframe = document.querySelector('iframe');
  iframe.setAttribute('id', 'player');
  const player = new YT.Player('player', {
    events: {
      onReady: onPlayerReady,
    },
  });
};

In this function, we will find parent element of the iframe, then add class into it.

Then we will call it one the youtube is loaded.

function onPlayerReady() {
  const iframeParent = window.frameElement.parentElement;
  iframeParent.classList.add('media--loaded');
}

This class will really helpful if you want to make sure the user only can click to play video once it's fully loaded.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Comments

  • Allowed HTML tags: <em> <strong> <cite> <blockquote cite> <ul type> <ol start type> <li> <dl> <dt> <dd> <p>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
  • Use [gist:#####] where ##### is your gist number to embed the gist
    You may also include a specific file within a multi-file gist with [gist:####:my_file].

Spread the word