I'm learning JavaScript by writing a Chrome extension for a website. The website has a section that displays a list of 4 videos, with a button to load more videos. When you click this button, it loads a new list of videos via an AJAX call.
I have a function, getNextVideo()
, which gets the URL of the next video in the list. For example, if you are on the third video, then it'll grab the URL for the fourth video. If you're on the fourth video, then it'll simulate a click (which loads the new list of videos) via a function getNextVideoList()
and then grab the first in the newly loaded list after a 1s timeout to wait for the DOM to update (I tried to use mutation observers but it was too complicated for my skill level).
function getNextVideo()
{
if (getVideoPosition() == 4)
{
function ad()
{
getVideo(1);
}
setTimeout(ad, 1000);
getNextVideoList();
}
else
{
var index = getVideoPosition() + 1;
return getVideo(index);
}
}
getVideoPosition()
gets the index of the video in the list using some simple jQuery nth-child selectors. It returns the values 1
, 2
, 3
, or 4
.
getVideo(n)
takes the index of the video (1, 2, 3, or 4) and returns the URL of that video. The returned value looks like this in the console: "http://video.example.com/video-id"
My problem is that when I run getNextVideo()
on a video that is 4th in the queue, I get undefined
returned in my console. How do I make the getNextVideo()
function return the URL of the first video in the list after the AJAX call and subsequent DOM update?