#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2

    Displaying a random background image


    Hello. I am trying to display a random background image from onClick. The images correspond to id's in a database. It works fine if I specify the image to change to but when I substitute the random variable it does not work. Please see the following code...


    Code:
    //find total number of rows
    t.executeSql('SELECT COUNT(*) AS count FROM notes LIMIT ?', [trNotes.limit],
    function(t, result) {
    var row2 = result.rows.item(0),
    opts = {};
                                    
    //get a random row
    var x = row2.count; 
    var rand = Math.floor(Math.random()*x) + 1;
                                    
    $("#page2").css("background-image","url(http://www.myserver.com/photo/4.jpg)");
    The above code works but when I change the following line it does not. Are there any errors on how I am including the 'rand' variable?

    Code:
    $("#page2").css("background-image","url(http://www.myserver.com/photo/' + rand + '.jpg)");
    Thanks for all help!
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,175
    Rep Power
    184
    Did you check the output for your "rand" variable; to see if it is giving you a corresponding number, that matches the name of a file, that exist in your directory? One thing you might try is adding single quotations in your background-image url parameter; like so:
    Code:
    $("#page2").css("background-image","url('http://www.myserver.com/photo/' + rand + '.jpg')");
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2
    Ahhh, my rand variable is not returning anything. I am looking into that. I will also try adding the single quotes. Thanks.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2
    Ok, I confirmed that my 'rand' variable is not null by using an alert. However, I cannot get it to work in my url.

    Code:
     alert('' + rand + ''); // 2 single quotes
    $("#page2").css("background-image","url('http://www.wddclients.com/app_iphone/Blur/photo/''+rand+''.jpg')");
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2
    Ok, I figured it out. I had to use double quotes around the variable...

    " + rand + "


    These darn quotes always mess me up.

    Thanks for your help! You pointed me in the right direction.

IMN logo majestic logo threadwatch logo seochat tools logo