1

i have six function like scan1(),scan2()...scan6(). each function loads different images. now i want to call functions randomly on each time page loads.

for example page load first time, call sacn4()

page load second time, call scan6()

page load third time, call scan1()

and so on

page load i mean page refresh/reload.

or help me in this code i am trying

var arr = ['scan1()', 'scan2()', 'scan3()'];
var ran = Math.floor(Math.random() * 6) + 1

$(document).ready(arr[ran]);

thanks

5 Answers5

1
$(function() {
    var arr = [scan1, scan2, scan3],
        rand = Math.floor(Math.random() * arr.length),
        func = arr[rand];

    func();
});
zerkms
  • 249,484
  • 69
  • 436
  • 539
0

This should fix it:

var arr = [scan1, scan2, scan3];
var ran = Math.floor(Math.random() * 6) + 1

$(document).ready(arr[ran]());

You need to populate your array with function objects, rather than strings containing the names of the functions. On the final line, when you say:

arr[ran]()

you retrieve a function from the array and then invoke it.

codebox
  • 19,927
  • 9
  • 63
  • 81
0

From here:

$(function() {
    var arr = ['scan1', 'scan2', 'scan3'];
    var ran = Math.floor(Math.random() * 3) + 1;
    window[arr[ran]]();
});
Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252
0

The functions are stored in your global object, so you don't need to store them in the array as 'functionName()', but rather as 'functionName'. Then call using call() or apply().

var arr = ['scan1', 'scan2', 'scan3'];
var ran = Math.floor(Math.random() * 6) + 1

$(document).ready(window[arr[ran]].call(this));
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
0

You should refactor your code, what you want to do can be done in a more simple approach, you dont need 6 functions one for each image, create just one scan() function, this function will have an array containing all images and then select one randomly, like this:

function scan() {
    var images = ['im1.jpg','im2.jpg','im3.jpg','im4.jpg','im5.jpg','im6.jpg'];
    var inumber = Math.floor((Math.random()* images.length)+1);

    var random_image = images[inumber-1];

    //Do whatever you want with random_image
    alert( random_image ); //Shows the random image
}

as a plus, with above code, you can even in the future add more images to the images array and they will be automatically included in the randomly selection.

With the above code, your document.ready will just be:

$(document).ready( scan() );
Nelson
  • 49,283
  • 8
  • 68
  • 81