M1X
M1X

Reputation: 5354

Insert YouTube iframe on hover

I want to insert an iframe when user hovers on a div but it dosen't seem to be working. It works pretty well without the hover event but not on hover function.

html:

<div class="video_wrap"></div>

css:

.video_wrap {
    width: 320px;
    height: 240px;
    background: #b30054;
}

js:

var tag = document.createElement('script'),
    firstScriptTag = document.getElementsByTagName('script')[0];

tag.src = "https://www.youtube.com/player_api";
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

$(".video_wrap").on({
    mouseenter: function () {

        $(this).attr('id', 'curr');

        var player;

        function onYouTubePlayerAPIReady() {
            player = new YT.Player('curr', {
                height: '240',
                width: '320',
                videoId: 'wJnnT1SGEsc',
            });
        };

    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

Fiddle: http://jsfiddle.net/508oknm7/4/

Upvotes: 0

Views: 83

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50787

You don't declare the onyoutubeready function within the event handler. That event is dispatched once the script has been loaded, it makes no sense. Instead, you just construct the player within the hover.

$(".video_wrap").on({
    mouseenter: function () {

        $(this).prop('id', 'curr');

        player = new YT.Player('curr', {
            height: '240',
            width: '320',
            videoId: 'wJnnT1SGEsc',
        });


    },
    mouseleave: function () {
        //stuff to do on mouse leave
    }
});

jsFiddle

Upvotes: 2

Related Questions