Under normal circumstances I am able to link Amazon Mechanical Turk users to my survey simply by copying and pasting the URL of my survey into the form. When users click this URL, they are sent to this page in a new tab.
I want to replace this fixed URL with a hyperlink that randomly redirects users to one out of four web pages. With help I was able to code the generation of an array of four different sites and the ability to randomly select and present one of these to the user. My problem with this code is that upon clicking this new (hyper)link, they are presented the URL to one of the sites in plain text, AND in the same window.
What I am trying to do is send users directly to one of the randomly selected sites in the array in a new tab when they click this URL. In short: making it behave the same as a direct hyperlink to an URL would do. The reason for this is that users will have to keep the page that redirects them to the different sites open as they will need to fill in a code after completing the survey.
I fail to understand why this is not already happening, and how I should adjust the code to make this possible. I would greatly appreciate help with solving this issue.
<a href="JavaScript:openSite()">Click to go to a random site</a>
<script>
var links = [
"google.com",
"youtube.com",
"stackoverflow.com",
"apple.com"]
var openSite = function() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
return link;
};
</script>
Try as follows
<a href="javascript:openSite()">Click to go to a random site</a>
<script>
var links = [
"google.com",
"youtube.com",
"stackoverflow.com",
"apple.com"]
var openSite = function() {
// get a random number between 0 and the number of links
var randIdx = Math.random() * links.length;
// round it, so it can be used as array index
randIdx = parseInt(randIdx, 10);
// construct the link to be opened
var link = 'http://' + links[randIdx];
var win = window.open(link, '_blank');
win.focus();
};
</script>