video src + random urls

hi guys, I’ve been searching for a while now. Can’t figure out a way to make this work. I have a youtube video player that starts to play when onClick a button. Its working fine with a single video, but im trying to make it work with random videos from a lsit. I found old forum advices but they aren’t working, it keeps loading only one video from the list.

here follows the code im currently using:


export function loadChillClassic_click(event) {
    const allUrls = [
     'https://www.youtube.com/watch?v=Y6nFoHIwXUw',
     'https://www.youtube.com/watch?v=Y6nFoHIwXUw',
     'https://www.youtube.com/watch?v=Y6nFoHIwXUw',
     'https://www.youtube.com/watch?v=Y6nFoHIwXUw'
    ];

$w.onReady( function() {
 const randomIndex = Math.floor(Math.random() * (allUrls.length -1));
 $w("#videoLivePL1").src = allUrls[randomIndex];
})
setTimeout(function() {
 $w('#videoLivePL1').play()
 $w('#videoLivePL1').unmute()
}, 1000);

Any tips on how it could work would be deeply appreciated!

Move the random index calc inside of the onReady() make it a let instead of const .

$w.onReady( function() {
    let randomIndex = Math.floor(Math.random() * (allUrls.length -1));

I have tried your code on my site and it worked perfectly for me. One thing I noticed is that you have the same video URL repeated a few times in the allUrls array.

hehhe I used it as example for i could not use the originals as it belongs to the client. Sorry, fogot to especify that in the question ^^.

note: to me what made it work was changing from “cosnt” to “let” like Yisrael adviced in
<let randomIndex = Math.floor(Math.random() * (allUrls.length -1));>

Thank you a lot Yisrael, changing for let made the deal! All working now.