Sunday, 29 September 2019

Last pressed index + 1?

I am using the youtube api to search for youtube videos. The videos will then be displayed on #searchBar with the video id ex. NJNlqeMM8Ns as data-video. I get the video id by pressing on a img:

<img data-video = "" src = "bilder/play.png" alt = "play" class = "knapp" width = "40" height = "40">

Which in my poorly understanding of javascript becomes (this). When I search for videos I will get more than one result which means that I will get more than one img tag.

In this case i want to play the next song when the first one is finished. I tried to get the index when i pressed on my img tag:

        $(".knapp").click(function(){
    var index = $(".knapp").index(this);
    alert(index);
    });

However, when I alerted the index after the video was finshed I always got the value 0 back.

So I thought i could do something like this:

function onPlayerStateChange(event) {
   if (event.data == YT.PlayerState.ENDED){
    playNext();
   }
}

$('#searchBar').on('click', '[data-video]', function(){
player.current_video = $(this).attr('data-video');
playVideo();
});

function playVideo(){
var video_id = player.current_video;
player.loadVideoById(video_id, 0, "large");
}

function playNext(){
var player.current_videon = **$(this + 1).attr('data-video');**
var next_id = player.current_videon;
player.loadVideoById(next_id, 0, "large");
}

But I'm not sure how to make it work, as you can see in the bold section, can I solve my problem like this or do I need another approach?

I tried the next() suggestion, but I think something is missing to complete the exchange

function playNext(){
player.current.videon = $(".knapp").next("[data-video]");
var video_idd = player.current.videon;
player.loadVideoById(video_idd, 0, "large");
}

With some research I found out that i need to set the value of the current video being played and also efter the video was done playing il add this number by 1. However even if it did make the next video play, i was unable to chose the song i wanted anymore...

    function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED){
    player.current_video++;
    playVideo();
}
}
var player = document.querySelector('iframe');
function onYouTubeIframeAPIReady() {
 player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '40mSZPyqpag',
playerVars: {rel: 0},
events: {
  'onStateChange': onPlayerStateChange
}
});
player.current_video = 0;
}

$('#searchBar').on('click', '[data-video]', function(){
 player.current_video = $(this).index();
 playVideo();
});

function playVideo(){
var video_id = $('[data-video]').eq(player.current_video).attr('data-video');
player.loadVideoById(video_id, 0, "large");
}  


from Last pressed index + 1?

No comments:

Post a Comment