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

Assign the array value to all inputs that share the same class tag

Does anyone know how to iterate through all tags with the same className and retrieve their values? var quantities = []; $(".add_more_items").each(function(){ quantities.push($(this).val()); }); Here is an example of the result: ['1&apo ...

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...

What could be causing my Bootstrap datepicker to malfunction?

A while ago, my Bootstrap datetimepicker component was functioning perfectly in my code. However, it has suddenly stopped working and I am seeking assistance to get it running smoothly again. Below is the HTML code snippet: <script src="https://cd ...

What is the best way to display link icons - as images or using CSS background-image URLs?

When designing a web UI, I am considering using iconography to represent actions such as adding, editing, deleting, and searching for items. However, I want to ensure that the purpose of each action is clear without displaying text and cluttering the UI sp ...

Adjusting animation placement when resizing the window

Is it possible to utilize jquery window.resize() to ensure that the positioning of the two donuts never interferes with the text in the middle of the home? I am unsure of how to connect the x and y values of the window size to adjust the top/left and botto ...

Adding text to a newly appended element using jQuery

I am confident in my ability to accomplish this task $('.intro').append('<p>this is my text</p>'); However, I have a question about how to add text to the new element by chaining it $('.intro').append(' ...

Using two different colors in text with CSS

Is it possible to have text in two different colors like this: https://i.stack.imgur.com/R40W1.png In terms of HTML, I tried looking it up but found answers related to:- https://i.stack.imgur.com/GRAfI.png ...

Is there a way to use moment js to change the date format to just show the month and year?

Want to transform the date time format using momentjs 2017-02-01T00:00:00.000Z into 02-2017 ( month-year ) Looking for a way to change the date format to display only month-year using momentjs? I attempted it like this: var MnthYr = moment(2017-02-01 ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Display toggle malfunctioning when switching tabs

I am currently working on implementing a search function with tabbed features. Everything seems to be displaying correctly without any errors. However, the issue arises when I try to click on any tab in order to show or hide specific content from other tab ...

Enhancing elements with fade-in effects upon hovering

Is there a way to incorporate a subtle fade in/fade out effect when hovering over items on this webpage: http://jsfiddle.net/7vKFN/ I'm curious about the best approach to achieve this using jQuery. var $container = $("#color-container"), ...

`Is there a way for Javascript to retrieve information sent from Python Flask's render_template() method?`

Issue: I am facing difficulties in retrieving and displaying the data that I send from Javascript code when the user visits the site's landing page. The data in question is a dataframe. Backend Python Code: from flask import Flask, render_template, ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...

Executing the `process.nextTick` function throws an error, causing the message: "Headers cannot be set once they have been sent."

I'm attempting to retrieve data from MongoDB within a Node.js file. I am encountering the following error: /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); Error: Can't ...

Is it possible to use just one <map> tag for multiple images in jQuery or JavaScript?

I have multiple images on my website <img usemap="#slideMap_branches" src="branches.png" width="890" height="270" alt="Slide 4"> <img usemap="#slideMap_order" src="order.png" width="890" height="270" alt="Slide 2"> <img usemap="#slideMap_c ...

Incorporating grids for a flickering drag and drop effect in Javascript

I have been working on developing a selection system for a tilemap image where users can select multiple tiles by dragging the mouse to increase the size of the selection container. However, I've noticed a flickering effect while holding down the mous ...

Webpack is notorious for creating multiple copies of images

Having an issue with Webpack where it's generating duplicate images, one of which is broken. I have an original image image, and after running Webpack, two duplicates are created. One works fine: image, but the other one is broken: image. I'm us ...

Failure of Ajax to populate dropdowns in Internet Explorer

I've been grappling with some code for the past couple of days and I'm stuck. I really need some help. Here's what I'm trying to achieve: Manually fill the first dropdown menu Retrieve the selected value from the first dropdown, use i ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...