So I’ve got this JavaScript array full of fifty YouTube video id’s and a while loop that writes the first two videos to the DOM. This code is being printed using PHP in case you’re wondering about the backslashes.
<script type="text/javascript">
var videoArr=["id1", "id2", etc.];
var i = 0;
while (i<2) {
document.write(\'<iframe width="400" height="225" src="http://www.youtube.com/embed/ \'+videoArr[i]+\'?rel=0&autohide=1&showinfo=0" frameborder="0" allowfullscreen></iframe>\');
i++;
}
</script>
So basically I need a ‘Previous’ and ‘Next’ button that will cycle through this array and write the next or previous two videos to the DOM. What’s the best way to do this?
You have declared
var iat global scope already, now you only need functions to increment or decrementiand append it to the DOM. Rather thandocument.write()when the DOM is already loaded, you ought to append them to the<body>.Create some new buttons and bind the functions
previousVideo()andnextVideo()to them.Edit: I just noticed you want to append two videos each time. In that case, just call the previous & next functions twice per button click. If you read to the ends of the array, only one will be added.