Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript [Solved] Unique random number

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #30303
    carlgordon
    Member

    Hi I’m looking to populate divs with a random background image. What I have so far is a script to generate a random number and then set the css background image using that number. What I can’t figure out how to do is to make sure that random number is unique so that no two images are the same.

    Here is what I have…

    $(document).ready(function(){

    bgImageTotal=77;

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud1').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud2').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud3').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud4').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud5').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud6').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud7').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud8').css('background-image', ('url("'+imgPath+'")'));

    randomNumber = Math.round(Math.random()*(bgImageTotal-1))+1;
    imgPath=('clouds/'+randomNumber+'.jpg');
    $('.cloud9').css('background-image', ('url("'+imgPath+'")'));

    });

    Please can someone help me? I'm a complete newbie with Jquery, so please be gentile.

    Cheers

    #79313
    lookslikepat
    Member

    Hi!

    Sorry for the multiple edits, I got a character or 2 messed up, had to make sure this worked…

    I’m assuming that all you want is a way to get a unique number, right?
    Create an array, with all the images. That’s my suggestion :)

    var imageCount = 77;
    var myImages = [];
    var i=0;
    for ( i; i myImages.push(i + ".jpg"); // or "prefix" + i + ".jpg"
    }

    To get a unique number from this array, make a function:

    function fetchRandomImage(myImages) {

    // Generate a random number based on the "length" of the array
    var randomNumber = Math.floor(Math.random()*myImages.length);

    // Get the value of that item in the array
    var randomImage = myImages[randomNumber];

    // remove that number from the array
    myImages.splice(randomNumber,1);

    // Finally, return the string that you just fetched from the array

    return randomImage;

    }

    Pass the array you just created to the function

    var randomImage = fetchRandomImage(myImages);

    And finally, use this string in your imgPath variable:

    var imgPath = "clouds/" + randomImage;

    If what you meant was generating 77 elements at the same time, let me know and I’ll re-post some ideas…

    Also, this assumes that you name your first image “0…” and your last “76…” if you have 77 images. Arrays are zero-based ;)

    Btw, is imgPath=('clouds/'+randomNumber+'.jpg') a typo? A string has to begin with ‘ or “…

    #79226
    lookslikepat
    Member

    This is how you generate 77 DIVs, looking like this:



    The first portion should be identical to the previous one I posted, however this also generates the DIVs and the classnumbers…

    // number of images
    var imageCount = 77;
    // this tells javascript myImages is an array
    var myImages = [];

    // this for loop fills the array with "1.jpg","2.jpg"...
    for ( var i=0; i // push is appending the new item into the array
    myImages.push(i + ".jpg"); // or "prefix" + i + ".jpg"
    }

    function fetchRandomImage(myImages) {
    // Generate a random number based on the "length" of the array
    var randomNumber = Math.floor(Math.random()*myImages.length);
    // Get the value of that item in the array
    var randomImage = myImages[randomNumber];
    // remove that number from the array
    myImages.splice(randomNumber,1);
    // Finally, return the string that you just fetched from the array
    return randomImage;
    }

    // this is just a counter for your css classes
    var classCounter = 1;

    // I made this for loop a little diff. - it lopps for as long as the array
    // has any items in it, and increments the classCounter instead
    for ( var forCounter = 0; forCounter // this variable fetches a unique random "number" from the array
    var randomImage = fetchRandomImage(myImages);
    // Everything so far has been "raw" javascript, this is the jQuery part
    $("
    ")
    .addClass("cloud" + classCounter)
    .css("background-image","url(./clouds/" + randomImage + ")")
    // I applied this to the BODY tag so you can see how it works
    // just change it into the target DIV or other element that you
    // which it to go into
    .appendTo($("body"));
    }

    // ! After this has run, the myImages array will be empty !

    You’ll probably come to a point where you realize, having spent some time with javascript, that this can be done several ways. I’m in the same boat you are, just started with javascript :)

    #78932
    carlgordon
    Member

    Thanks lookslikepat.

    I had my question answered on another forum and I adapted my script to this…


    $(function () {
    var ar = [];
    function returnRandomUnique() {
    if ( ar.length) {
    return 'url(clouds/' + ar.splice(Math.floor(Math.random() * ar.length) ,1) + '.jpg)';
    } else {
    for (var i = 76; i > 0; i--)
    ar[ar.length] = i;
    }
    }
    returnRandomUnique();
    $('.cloud1').css('background-image', returnRandomUnique());

    $('.cloud15').css('background-image', returnRandomUnique());
    });

    Your script looks good with nice descriptions. Many thanks for your time.

    #78934
    lookslikepat
    Member

    Don’t mention it! Glad you found your answer.
    This tought me something as well, .splice() not only removes the item from the array, it also returns it :)

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.