Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a class instead of id for new YT.Player()

In the example given here https://developers.google.com/youtube/iframe_api_reference you can see that instead of using standard css selector syntax there's a custom string syntax that seems to only refer to id.

<div id="player"></div>

// note no 'var' and yet this will work in strict mode
// since 'player' is being implicitly grabbed from the dom
player = new YT.Player('player', ...);

This of course creates the problem of leaking a global variable for whatever the id is named, which is something that I try to avoid (because it creates a loophole for strict mode and is just confusing and unexpected behavior).

A workaround is to hyphenate the name so that it can't be accessed from the global space

<div id="js-player"></div>

// now window['js-player'] is guarded from accidental access
var player = new YT.Player('js-player', ...);

but the bottom line is that using ids is just bad practice and I prefer to avoid them altogether since classes work nicely and don't have the weird side affects.

like image 816
coolaj86 Avatar asked Jul 31 '15 21:07

coolaj86


People also ask

What is api iFrame?

Developers can use the iFrame API to programmatically create and interact with an Embed or with multiple Embeds in the same web app. The iFrame API includes methods that you can use to start playback, change the content rendering in an Embed, or stop playback.

What is YT player?

Youtube Player. YTPlayer helps you control all of your opened Youtube videos either using keyboard shortcuts or directly using its popup window. The player has audio controls + focus button which focus on a tab, skip button which skip the ad if any, and a button to show suggested youtube videos (exclamation mark icon).

How do I unMute an iFrame video?

Until and unless you have allow="autoplay;" in your iframe tag you wont be able to unmute the video. Add this attribute and further unMute function will work. Save this answer.


1 Answers

Might be a bit late for an answer but anyways ...

Just pass the selector like so

var player = new YT.Player(
                 document.querySelector('.your-class'), 
                 ... API Stuff ...
             );

Of course, you could use jQuery or any other vanilla JS method for selecting elements.

var player = new YT.Player(
                 $('.your-class')[0], 
                 ... API Stuff ...
             );

If you use a method that returns a node list be sure to loop trough the items like so: Todd Motto - Looping Through NodeLists / Arrays

like image 58
Bjørn Lindner Avatar answered Sep 30 '22 19:09

Bjørn Lindner