Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9197909
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T22:10:37+00:00 2026-06-17T22:10:37+00:00

I’m trying to position images within a banner div on a web page. The

  • 0

I’m trying to position images within a banner div on a web page. The images need to be positioned ‘randomly’ along the x axis (using the CSS left property), so they don’t always appear the same when the page is loaded. I have the following script to do this (it also sets a random delay so the images appear in a different temporal order each time:

for (var i = 1; i <= 5; i++) {

    var delay = Math.floor(Math.random() * 800) + 1;
    var xPos = Math.floor(Math.random() * 900) + 1;

    $('#item'+i).css('left',xPos+'px').delay(delay).animate({ top: 18 }, { duration: 1000, easing: 'easeOutBounce' });

}

However, the problem is that there’s very often too much overlap with the images and they’re hidden behind one another. So I’d like to skew the randomness so that there’s at least 100px difference between all of the xPos variables. This should give me a random-looking appearance but keeping the items mostly visible too.

There must be a word to describe this kind of thing but having searched I just can’t find anything useful to indicate how to achieve it.

Can anyone point me in the right direction here?

Many thanks.

EDIT:

Okay, so having a go at rolling my own functions to do this. I think I’m almost there. What I’m doing is creating an initial random number and adding this to an array, then looping through each of the 5 items and generating another random number, then comparing this to make sure it’s more than 100 different to anything currently in the array.

The code is like this (not all of my variables are being used currently – it’s a work in progress!):

function randomImagePlacement() {
    var containerWidth = 940;                   // Width of container element
    var itemWidth = 267;                        // Width of item (taking into account rotation)
    var minX = 0;                               // Minimum left position of an item
    var maxX = containerWidth - itemWidth;      // Maximum left position of an item
    var minSeparation = 100;                    // Minimum number of pixels of separation between items
    var numberOfItems = 5;                      // Total number of items
    var randomNumbers = [];                     // Array 'container' to hold random numbers

    for (var i = 1; i <= numberOfItems; i++) {

        if (i == 1) {
            var firstRandomNumber = Math.floor(Math.random() * 700) + 1;
                    randomNumbers.push(firstRandomNumber);
                    console.log('First random number: ' + firstRandomNumber);
        } else {
                    var newRandomNumber = Math.floor(Math.random() * 700) + 1;

            /*
            This if/else block works okay but it doesn't keep checking differences until the criteria is met
            if (checkDiff(newRandomNumber, randomNumbers)) {
                        console.log('New number (' + newRandomNumber + ') sufficiently different enough');
                        randomNumbers.push(newRandomNumber);
            } else {
                        console.log('New number (' + newRandomNumber + ') NOT sufficiently different enough');
            }
            */
            /* This do/while block is my attempt at trying to run the check diff function until the criteria is met, but it just results in the browser crashing */     
            do {
                        randomNumbers.push(newRandomNumber);
            } while (checkDiff(newRandomNumber, randomNumbers) == true);

        }

    }

    for (var i = 0; i < randomNumbers.length; i++) {
        console.log('From final array: ' + randomNumbers[i]);
    }

}


function checkDiff(newRandomNumber, currentArray) {
    console.log('newRandomNumber = ' + newRandomNumber);

    var proximityMatch = false;
    for (var i = 0; i < currentArray.length; i++) {
        console.log('Diff between ' + currentArray[i] + ' and ' + newRandomNumber + ' = ' + Math.abs(currentArray[i] - newRandomNumber));
        if (Math.abs(currentArray[i] - newRandomNumber) > 100) {
            proximityMatch = true;
        }
    }
    if (proximityMatch == true) {
        return true;
    } else {
        return false;
    }
}

randomImagePlacement();

Basically where it’s failing is in the do/while loop above. I’m not sure of the correct way to do something like this, but I basically need to say “Keep running the checkDiff function until it returns true; when it does return true add the newRandomNumber to the array; if it doesn’t return true run it again”.

Can anyone help me out on this?

Many thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T22:10:38+00:00Added an answer on June 17, 2026 at 10:10 pm

    UPDATE

    Sorry, I didn’t realize you needed that comparison across all generated values. This will work:

    var isLessThanMinSeparation = function checkDiff(randomNumber, randomNumbers, minSeparation) {
        var lessThan100 = false,                // Flag for whether minSeparation has been maintained
            i = 0;                              // Incrementer
        console.log('randomNumber = ' + randomNumber);
        for (i = 0; i < randomNumbers.length; i += 1) {
            console.log('Diff between ' + randomNumbers[i] + ' and ' + randomNumber + ' = ' + Math.abs(randomNumbers[i] - randomNumber));
            lessThan100 = lessThan100 || Math.abs(randomNumbers[i] - randomNumber) <= minSeparation;
        }
        return lessThan100;
    };
    var randomImagePlacement = function randomImagePlacement(numberOfItems, minSeparation) {
        //numberOfItems = 5,                    // Total number of items
        //minSeparation = 100,                  // Minimum number of pixels of separation between items
        var randomNumbers = [],                 // Array 'container' to hold random numbers
            randomNumber = 0,                   // Random number
            i = 0;                              // Incrementer
        for (i = 1; i <= numberOfItems; i += 1) {
            while (isLessThanMinSeparation(randomNumber, randomNumbers, minSeparation)) {
                randomNumber = Math.floor(Math.random() * 700) + 1;
            }
            randomNumbers.push(randomNumber);
        }
        return randomNumbers;
    };
    console.log(randomImagePlacement(5, 100));
    

    The way I’d accomplish this would be to:

    1. Store the last randomly-assigned position
    2. Use a loop (with a minimum run of once) to assign the new randomly-assigned position
    3. Compare the new randomly-assigned position and re-enter the loop if the difference < 100

    An example:

    var randomizeImgPlacement = function randomizeImgPlacement() {
        var i = 0,
            delay = 0,
            xPos = 0,
            lastPos = 1000; //Default to 1000 so very first assignment has at least 100 difference
        for (i = 1; i <= 5; i += 1) {
            delay = Math.floor(Math.random() * 800) + 1;
            do { //loop assignment of xPos
                xPos = Math.floor(Math.random() * 900) + 1;
            } while (Math.abs(xPos) - Math.abs(lastPos) >= 100); // while difference is < 100
            $('#item' + i).css('left', xPos + 'px').delay(delay).animate({
                top: 18
            }, {
                duration: 1000,
                easing: 'easeOutBounce'
            });
            lastPos = xPos; //store lastPos for loop comparison
        }
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Basically, what I'm trying to create is a page of div tags, each has
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I am using JSon response to parse title,date content and thumbnail images and place
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have thousands of HTML files to process using Groovy/Java and I need to
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
I'm making a simple page using Google Maps API 3. My first. One marker
I am using jsonparser to parse data and images obtained from json response. When
I am trying to understand how to use SyndicationItem to display feed which is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.