James James - 5 months ago 24
Javascript Question

Using jQuery to foreach iframe src and get ID and action via functions

I know i have made a little mess of this, im new to jquery and JS... would someone mind helping me rewrite these functions correctly using j query as know its standard JS which was working fine with the manual HTML markup but i now also need to go through page and find iframes with youtube src and take ID and then recreate them with the first example markup... but im totally stuck... think i have it more or less there but lost of where to go to now.

fiddle: https://jsfiddle.net/yurt5bb6/

First example uses my markup:

<div class="video-container">
<div class="video-player" data-id="Cv_2mp3X868"></div>

Which works as i need, however i think now i need to foreach on load and create that same markup from iframe embeds the functions should be better... sorry if im not explaining wlel but if you see fiddle you know what im trying to do :)

Thanks for anyone's help, think ive done ok getting this far being new lol


function createThumb(id) {
return '<img class="youtube-thumb" src="//i.ytimg.com/vi/' + id + '/hqdefault.jpg"><div class="play-button"></div>';

function createIframe() {
var iframe = $("iframe");
iframe.attr("src", "//www.youtube.com/embed/" + this.parentNode.dataset.id + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
iframe.attr("frameborder", "0");
iframe.attr("id", "youtube-iframe");
this.parentNode.replaceChild(iframe, this);

$(document).ready(function() {

// build video from default markup
var defaultVideo = $(".video-player");
$(defaultVideo).each(function (index, value){
var p = $('<div></div>');
p.innerHTML = createThumb(v[n].dataset.id);
p.onclick = createIframe;

// search for social embeds and recreate to our markup
$('iframe[src*="youtube.com"]').each(function() {
var loadedVideoURL = $('iframe').attr('src').match(/[^/]*$/)[0];


Tyr Tyr

I've tried to clean up the messy mix of native JS and jQuery and made some edits to your fiddle: https://jsfiddle.net/yurt5bb6/2/

Default function:

(function() {
    $.each($('.video-player'), function() {
        $(this).on('click', videoIframe);

    $.each($('iframe'), function() {
        // Rebuild the given template
        var player = $('<div class="video-player">');

        // Strip youtube video id for data-id attribute
        var id = $(this).attr('src');
        id = id.substr(id.lastIndexOf("/")+1);
        player.attr('data-id', id);

        player.on('click', videoIframe);

        var videoContainer = $('<div class="video-container">');

Iframe render function:

function videoIframe() {
    var iframe = $('<iframe>');
    iframe.attr("src", "//www.youtube.com/embed/" + $(this).attr('data-id') + "?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&controls=0&showinfo=0");
    iframe.attr("frameborder", "0");

Also changed the CSS, made a class instead of id for youtube-iframe.