Question

I'm creating a qualtrics survey and I'd like to create a way to randomize which images participants will see on a given questions

Here's the basic code I have so far

var banner = document.getElementById('banner');
var picture = document.getElementById('picture');

banner.style.display = 'none';
picture.style.display = 'none';

images = [banner, picture];

function randomImage() {
    var idx = Math.floor(Math.random(0, images.length - 1) * 10);

    return images[idx];
};

var image1 = randomImage(); 
image1.style.display = 'block';

Where 'picture' and 'banner' are the ids of two images. However, this doesn't seem to work, the images disappear but a random image does not reappear. Any advice on a better way to make this function?

Was it helpful?

Solution

Should be...

var idx = Math.floor(Math.random() * images.length);

... as at the moment you for some reason multiply the result by 10, having quite a low chance for the final result to be either 0 or 1.

Note that Math.random() doesn't take any arguments: it always generates a number in [0, 1) range.

OTHER TIPS

Math.random() does not take any parameters, and returns a number between 0 and 1. Instead, use the following formula:

var randomNumber = Math.floor(Math.random() * MAX_PLUS_ONE);

Where MAX_PLUS_ONE is one more than the maximum number you want generated. In your case:

var idx = Math.floor(Math.random() * images.length);

images.length works here because the last index (largest number idx will be) will be one less than images.length

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top