bardic bardic - 3 years ago 85
Ajax Question

Math.floor(Math.random() * val.length) returns a letter not a number

I am trying to get a single random background image when someone visits/refreshes the page.

Writing out the array, like below, produces the desired outcome but I'd like to pull from a folder.

$(document).ready(function() {

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

$('#backgroundImage').attr('src',images[randomNumber]); // Random image


Using an ajax request, as below, almost works except Math.floor() returns a letter or special character like

img alt="" id="backgroundImage" src="g"

and not

img alt="" id="backgroundImage" src="./images/02.jpg"


var images = "images/";

url : images,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("body").append( "<img src='" + images + val[Math.floor(Math.random() * val.length)] +"'>" );

Direction would be much appreciated.

Answer Source

What you're doing right now with val[Math.floor(Math.random() * val.length)] is picking a random character from the string val (the value of the href attribute on the a element in question).

You probably want to make an array of all the images from the <a> then use the original code to get a random one from that array

var imgArray = $(data).find("a").filter(function(){
  return this.href.match(/\.(jpe?g|png|gif)$/)
    return images + this.href

var randomNumber = Math.floor(Math.random() * imgArray.length);         
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download