How do I make a random link embed button?

Hi there. I have almost no coding experience, but I want to put a button on my Wix site that will randomly select a link from a list and then embed that site below the button.

I have found this code from this forum. It redirects you to a random site but does not embed that site.

import   wixLocation from 'wix-location';
 $w.onReady(function(){
 const   allUrls = [
 'https://example .com',
 'https://google .com',
 'https://whatever .com',
];
 const   randomIndex = Math.floor(Math.random() * (allUrls.length - 1));
 $w('#button1').link   = allUrls[randomIndex];
 });
 //Add   your code for this event here:
 export function   button1_click(event) {
 //Add   your code for this event here:
 console.log(   $w('#button1').link)
 wixLocation.to($w('#button1').link);
 }

Thank you in advance for your help.

Add an iframe (aka htmlComponent) and do something like:

const   allUrls = [
 'https://example.com',
 'https://google.com',
 'https://whatever.com',
];
$w.onReady(() => {
$w('#button1').onClick(() => {
$w('#htmlComponent1').src = allUrls[Math.floor(Math.random() * (allUrls.length - 1))];
})
});

Awesome thanks! Is there any way to add a button to open whatever is embedded in a new tab? Some functionalities of the embedded websites seem not to work when they are embedded.

@maxinc1234 If you wish to get a new webpage in a new tab:

 const allUrls = [
 'https://example.com',
 'https://google.com',
 'https://whatever.com',
];
$w.onReady(() => {
$w('#button1').target = '_blank';
$w('#button1').link = allUrls[Math.floor(Math.random() * (allUrls.length - 1))];
});

But this will set the link randomly on page load. If you want to change it on every click, you’ll have to modify this code a little bit.

@jonatandor35 Ok. I’m very new at this coding stuff, how would I do that? Thanks for all your help.

1 Like