I want to use the YouTube Player API to call a single function that will stop an embedded YT video (loaded dynamically on the page with JS and jQuery) from playing on a button click.
I'm admittedly (very) new to working with APIs for web development and despite reading through several of the other answers (such as here, here and here), I am still confused as to the necessity of the different JS components.
I have a code block that is dynamically appended multiple times to the HTML page, with the YouTube URL changing for each entry based on a separate JSON file. The added code is as follows...
<li>
<section class="youtube-video">
<iframe src="'theLoadedURL'?enablejsapi=1&rel=0" frameborder="0" allowfullscreen="1">
</iframe>
</section>
</li>
... and then I have added the <script>
tag at the bottom of the <body>
that loads(?) the API...
<script src="https://www.youtube.com/iframe_api"></script>
... and finally a simple button for demonstration.
<button> Stop Video </button>
I was hoping that there would be a way to then simply call the player.stopVideo();
function from the API and have it affect the already-embedded iFrame on the button click, something like...
$('button').on('click', function () {
$('.youtube-video iframe').stopVideo();
});
... but alas, it doesn't seem to be that simple!
The documentation and other answers appear to suggest defining various variables and functions for the player, or deal with loading videos manually (rather than dynamically, as in this case); but it seems unnecessarily complex for an element that is already loaded on the page - is there something that I'm missing or an obvious way of simplifying things?
Detailed answers would be much appreciated as I'm still getting to grips with JS in general.
Thanks! :)