javascript - Generating random result from array -
i trying generate random result array using javascript. goal is, when user clicks button, want grab random result array named 'favorites'. works once page refreshed, when click @ second time, returns 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 favorite site " + favorite; alert(postmessage); });
try 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 favorite site " + 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 fair dice roll } }; })(jquery); updated fiddle:
thanks,
siva
Comments
Post a Comment