Reputation: 5
I want to make an iframe on my website that loads a random URL from a list. I tried this
<html>
<head>
</head>
<body>
<iframe class="frame" src="" style="width:200px; height: 200px"></iframe>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var cat1 = [
"https://www.youtube.com/watch?v=2XG_0iV2B40",
"https://www.youtube.com/watch?v=QnxpHIl5Ynw",
];
var myFrame = document.getElementsByClassName("frame");
function getRandomUrl(myFrame) {
var index = Math.floor(Math.random() * cat1.length);
var url = cat1[index];
myFrame.src = url;
}
function codeAddress() {
getRandomUrl(myFrame);
}
</script>
<script type="text/javascript">
codeAddress();
</script>
</body>
</html>
but it didn't work. I tried basically everything I could find, nothing worked and I don't understand why. Any help is appreciated. Thanks.
Upvotes: 0
Views: 2821
Reputation: 42364
The problem is that you are using document.getElementsByClassName("frame")
, which returns a collection of all of the elements with that class name. To access your specific frame, you need to access the first element with document.getElementsByClassName("frame")[0]
.
In addition to this, you need to use YouTube's embed link (https://www.youtube.com/embed/[videoID]
), rather than linking to the video directly through ?v=videoID
.
I've gone ahead and updated your links for you, corrected the variable, and logged the video source in the console. Clicking 'Run code snippet' multiple times will change the video randomly:
var cat1 = [
"https://www.youtube.com/embed/8PIPyPMNnp8",
"https://www.youtube.com/embed/gM2KaaVXs_g",
];
var myFrame = document.getElementsByClassName("frame")[0];
function getRandomUrl(myFrame) {
var index = Math.floor(Math.random() * cat1.length);
var url = cat1[index];
myFrame.src = url;
}
function codeAddress() {
getRandomUrl(myFrame);
}
codeAddress();
console.log(myFrame.src);
<iframe class="frame" src="" style="width:200px; height: 200px"></iframe>
Hope this helps! :)
Upvotes: 3