Position div elements randomly on the webpage when it first loads

I am trying to achieve a set of divs that will appear randomly on the page when it loads. Currently, I have the divs moving around the viewport in a random manner, but they all seem to load in the top left corner.

This is the method I am currently using: (https://jsfiddle.net/j2PAb/634/)

$(document).ready(function() {
    animateDiv($('.a'));
    animateDiv($('.b'));
    animateDiv($('.c'));});

function makeNewPosition($container) {

// Get viewport dimensions (remove the dimension of the div)
var h = $container.height() - 50;
var w = $container.width() - 50;

var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);

return [nh, nw];}


function animateDiv($target) {
var newq = makeNewPosition($target.parent());
var oldq = $target.offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);

$target.animate({
    top: newq[0],
    left: newq[1]
}, speed, function() {
    animateDiv($target);
});

};

function calcSpeed(prev, next) {

var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);

var greatest = x > y ? x : y;

var speedModifier = .1;

var speed = Math.ceil(greatest / speedModifier);

return speed;}

Answer №1

To set the initial positions of div elements, you can simply define the top and left properties as shown in this example

div.a {
    width: 50px;
    height: 50px;
    background-color: red;
    position: fixed;
    top: 300px;
    left: 10px;
}
div.b {
    width: 50px;
    height: 50px;
    background-color: blue;
    position: fixed;
    top: 100px;
    left: 50px;
}
div.c {
    width: 50px;
    height: 50px;
    background-color: green;
    position: fixed;
    top: 150px;
    left: 200px;
}

Answer №2

To ensure smooth animation, it is important to set random values for the top and left positions of these divs before initiating the animation.

Here's an example of how you can achieve this:

function initializeAnimation($target) {
    var newCoordinates = generateRandomPosition($target.parent());
    $target.css({top:  newCoordinates[0], left: newCoordinates[1]});
};

Take a look at the updated fiddle for reference.

Answer №3

Implement a method for initializing the position of each div element.

Here is an example:

function setInitialDivPosition(target) {
  var newPosition = calculateNewPosition(target.parent());
  target.css({top:  newPosition[0], left: newPosition[1]});
  animateDiv(target.show());
}

Additionally, hide the div elements initially to prevent the user from noticing the movement:

div.a, div.b, div.c {
  display: none;
}

The updated code can be viewed on this fiddle:

$(document).ready(function() {
  setInitialDivPosition($('.a'));
  setInitialDivPosition($('.b'));
  setInitialDivPosition($('.c'));
});

function setInitialDivPosition(target) {
  var newPosition = calculateNewPosition(target.parent());
  target.css({
    top: newPosition[0],
    left: newPosition[1]
  });
  animateDiv(target.show());
}

function calculateNewPosition($container) {
  var h = $container.height() - 50;
  var w = $container.width() - 50;

  var nh = Math.floor(Math.random() * h);
  var nw = Math.floor(Math.random() * w);

  return [nh, nw];
}

function animateDiv($target) {
  var newq = calculateNewPosition($target.parent());
  var oldq = $target.offset();
  var speed = calculateSpeed([oldq.top, oldq.left], newq);

  $target.animate({
    top: newq[0],
    left: newq[1]
  }, speed, function() {
    animateDiv($target);
  });

};

function calculateSpeed(prev, next) {

  var x = Math.abs(prev[1] - next[1]);
  var y = Math.abs(prev[0] - next[0]);

  var greatest = x > y ? x : y;

  var speedModifier = .1;

  var speed = Math.ceil(greatest / speedModifier);

  return speed;

}
div#container {
  height: 500px;
  width: 500px;
}
div.a,
div.b,
div.c {
  display: none;
}
div.a {
  width: 50px;
  height: 50px;
  background-color: red;
  position: fixed;
}
div.b {
  width: 50px;
  height: 50px;
  background-color: blue;
  position: fixed;
}
div.c {
  width: 50px;
  height: 50px;
  background-color: green;
  position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class='a'></div>
  <div class='b'></div>
  <div class='c'></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

Automatically adjusting jQuery script now functions on all hyperlinks for seamless resizing

I am attempting to create a rollover script that will resize my social network links when hovered over. The desired effect is for the 32px square icon to expand and display the trailing address. For example, when hovering over the Facebook link, it should ...

How to incorporate a routing file within another routing file in Node.js

I have structured my routes as follows: / /business /business/stuff1 /business/stuff2 /business/admin For /business, I am using a separate file for the routing and functions. And similarly, for /business/admin, I also want to use a separate file f ...

What is the best way to create a seamless change from a black to white invert filter?

I'm currently working on a project where I need to change my icons from black to white. After some research, I found that the best way to do this is by using filter: invert(100%). However, when I try to transition it, the change happens abruptly after ...

Interacting with a C# Web Service Using JQuery

I've set up a JSON web service in C# and I'm working on creating a custom HTML page to interact with it. http://localhost:25524/DBService.svc/json/db=TestDB/query=none When I input this URL into my browser, I expect to receive JSON formatted da ...

CSS animations - transitioning opacity in and out

Looking to add some CSS animations to a menu but running into some issues. I've got the code below for the menu to fade in on hover, but can't quite figure out how to make it fade out smoothly as well. I've tried a few approaches, but all I ...

Each time the server restarts, Express.js will run a function asynchronously

Looking for guidance on implementing a function in my Express.js app that can fetch data from the database and then cache it into Redis. The goal is to have this function executed only upon restarting the Web server. Any suggestions on how I can achieve t ...

Attempting to deploy my initial Google Cloud Function, encountering an error message indicating that Express is not detected

Currently in the process of deploying my first Google Cloud function, the code for which can be found here: https://github.com/rldaulton/GCF-Stripe/blob/master/Charge%20Customer/index.js The code starts with the following line: var app = require('e ...

The ReactJS component is unable to resolve the specified domain name

Whenever I utilize a component like const React = require('react'); const dns = require('dns'); class DnsResolver extends React.Component { componentDidMount() { dns.resolve('https://www.google.com', (err, addres ...

Creating a custom styled Drawer with flexbox styling using ReactJS, MUIv5, and the styled-engine-sc library

Hello community, I am currently working on implementing a custom styled drawer within a flexbox container using the styled-engine-sc. I started with a template and tried to convert it into styled-components. Here is the source: https://codesandbox.io/s/vm ...

Interconnected realms communication

I'm currently in the process of developing a Facebook iframe app. At one point, I initiate a friends dialog from Facebook and embed an HTML button to add some customized functionality for my app. dialog = FB.ui({ method:'fbml.di ...

When entering a sub-URL into the browser address bar, the routes do not display as expected

I am encountering an issue with navigating to different routes within my React application. While the home route is visible and functions properly when I start the app locally (npm run dev), I am unable to access other routes. No errors are displayed in t ...

Displaying limited items based on conditions in CSS

If there are 10 <p> tags, is it possible to limit them to only 5 by hiding the other 5 using CSS? Do I need to add a class five times with nth-child? Can CSS accommodate conditions for this purpose? Considering that the number of <p> tags is ...

What is the best way to make an AJAX request for an image src that updates every 3 minutes?

I've been trying to fetch the src attribute of an image on a website. The source changes approximately every 10 minutes, making it impossible for me to simply copy and paste the link of the image. I have been searching for a solution for a while now b ...

Maintain the state of various panels on page load with the Bootstrap Accordion feature

I have implemented a Bootstrap accordion on my form page which allows users to open multiple panels simultaneously. Upon submitting the form, I want to preserve the state of any open Bootstrap accordion panels. To achieve this, I utilized code from stack ...

Difficulty in utilising jQuery to serialize HTML form

Hey there, I'm just starting out with ASP.NET development and I'm having trouble figuring out how to properly serialize a form using jQuery. Check out this screenshot for more details: https://i.stack.imgur.com/0UFLX.png <html xmlns="http://w ...

Next.js allows you to create a single page that corresponds to the root path '/' as well as a dynamic route '/param'

I have a single-page website built with Next.js. The home page, which displays a list of products, is located at route / and the corresponding code can be found in pages/index.js. Each product has an id, allowing users to jump directly to it using /#produc ...

Ways to automatically check a checkbox using jQuery

Is there a way to use jQuery to programmatically click a checkbox? I am trying to create a hidden checkbox that will be checked when a user clicks on a specific element, but my current code is not functioning as expected and I am unsure why. You can view ...