0

I am trying to generate a random result from array using JavaScript. My goal is, when the user clicks the button, I want to grab a random result from array named 'favorites'. It only works once the page is refreshed, but when you click it at the second time, it returns the same result.

$('#button').click(function(){
        var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];
        var favorite = favorites[Math.floor(Math.random() * favorites.length)];
        var postmessage = "hi my favorite site is " + favorite;
        alert(postmessage);
    });
2
  • 5
    seems fine to me jsfiddle.net/arunpjohny/Sj74K/1 Commented May 22, 2013 at 4:17
  • I would move the array outside but it looks ok Commented May 22, 2013 at 4:18

1 Answer 1

1

Try the below code.

$('#button').click(function(){
    var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];
    var favorite = $.rand(favorites);;
    var postmessage = "hi my favorite site is " + favorite;
    alert(postmessage);
});


(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
})(jQuery);

updated fiddle:

http://jsfiddle.net/Sj74K/2/

Thanks,

Siva

Sign up to request clarification or add additional context in comments.

1 Comment

why? we need to check the type by using "===" only. am i right ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.