Utilizing jQuery to round numbers and dynamically move div elements around a webpage in a random fashion

I am looking to add some randomness to the movement of each div on a webpage. The current code I have moves all divs together, but I want them to move independently in different directions. How can I achieve this unique motion for each div?

$(document).ready(function(){
animateDiv();

});

function makeNewPosition(){

    // Retrieve viewport dimensions (considering the size of the div)
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

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

    return [nh,nw];    

    }

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

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

    };

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 = 0.1;

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

    return speed;

}

here is the code

Answer №1

edit to ensure the flow is consistent

function animateAllDivs () {
     $('.a').each(function() {animateDiv($(this));});
}

function animateDiv ($e){
     var newCoordinates = generateNewPosition();
     var oldCoordinates = $(this).offset();
     var animationSpeed = calculateAnimationSpeed([oldCoordinates.top, oldCoordinates.left], newCoordinates);
     
     $e.animate({ top: newCoordinates[0], left: newCoordinates[1] }, animationSpeed, function() {
          animateDiv($e); 
     });
}

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

Exploring the Depths of React Routing: The Power

I'm currently diving into React and trying to figure out how to create dynamic routes similar to partial pages in Angular. Here is my main App component: import React from 'react'; import Header from '../common/Header'; export d ...

Utilizing conditional statements within JSX in React

My current project involves creating a list in React using an array. The array contains information about different people, such as their name, website, and email address. const persons = [ { name: 'A', website: 'http://google.com' } ...

Dynamically adjust the gage value

Currently, I am working on a fitness application that involves showcasing BMI data using a gauge. However, I am struggling to figure out how to dynamically change the value of the gauge. In addition, when trying to implement the gauge script on button cl ...

Ways to activate flashlight on mobile using React.Js

Is it possible to control the torch light of a mobile device by toggling a button? https://i.stack.imgur.com/x9nIf.png <IconButton onClick={() => setFlashOn(!flashOn)} style={{ position: "absolute", right: 80, top: 20, zIndex: ...

What is the best method for asynchronously injecting and providing data?

Within my page, I have implemented an asynchronous fetch method to initialize data: async fetch() { const res = await requestApi(this, '/database'); this.sliderData = res.homeSlider; this.modelData = res.model; ... } To pass thi ...

The jQuery Click function is being triggered repeatedly

Below is a code snippet to examine: $(function(){ $(".notes").click(function(){ console.log('hi'); }) }) <a data-shipmentid="1" href="#" class="notes btn btn-primary btn-xs">Notes</a> <a data-sh ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...

The Jquery code encountered an issue where it was unable to access the property 'length' of an undefined

My goal is to submit a form using jQuery and AJAX, which includes file upload functionality. The challenge I'm facing is that the forms are dynamically created, so I need to identify which form was clicked and retrieve its input values. $(document).r ...

Issue with undefined object values in Internet Explorer

Within the workflow of an enterprise application, the following process takes place: Each service page features a "search box" where users can type something, triggering a call to a Struts 2 action through jQuery autocompleter. Upon the action call, Hibe ...

Tips for maintaining the integrity of an Array when passing it as an argument to a function in Javascript

I am working with an Array of objects called A There are 2 different drawing functions that make changes to A in their own unique ways. I want to preserve the original state of A. Are there best practices for achieving this? My current approach feels a bi ...

Detecting collisions with spheres using Three.js Raycaster

I came across an example from a previously answered question on this site: Three Js Object3D Button Group Detect Single Object Click While Mouse Movement Causes Object3D Button Group Zoomi As I tried to customize it to fit my needs, I encountered a few is ...

Opacity for ghost images in HTML5 drag-and-drop interface

Is there a way to make the ghost image for draggable elements in Chrome render on a transparent background, similar to how Firefox does it? I'm seeing that in Chrome (Chromium 45), the ghost image is displayed on a white background. For Example: http ...

Utilizing PHP and Ajax to Transfer Selected Option into Input Field

I need a solution to automatically transfer the selected value/option from a drop down menu into an input field without any page refresh. Ideally, I would like this functionality to work seamlessly without requiring an extra button click, so that the val ...

Is there a way to set an image as the background for several components in ReactJS?

I am trying to add an image as a background where various components like video, login, and bottom component will be placed on top of it. Can anyone help me with the correct code structure for achieving this in React? I am quite new to React development. ...

Arranging based on attribute data

I'm currently working on organizing a collection of divs that have unique custom data attributes which I aim to sort based on user selection. For instance, if 'followers' is chosen, the .box elements will be arranged according to their data- ...

Tips for modifying a JSON file within a React production deployment

I have been facing an issue in my development build where I have a JSON file containing crucial data, and I need to update this data in the production build. So far, I have used npm run build to create the build, but I am unable to locate the JSON file. ...

Is it possible to redirect any web traffic using an authentication script?

Scenario: I'm currently working on a social networking project and I'm looking for a way to validate every redirect or refresh by directing the user through another script before reaching their final destination. I've considered using a &apo ...

Understanding how to use Vuejs Components across multiple DOM elements, as well as how to initialize a Vue instance and utilize the "el

Imagine transitioning from the jQuery realm. If you are working with a component myPlugin (jQuery plug-in, such as a tool that displays tooltips when hovering over specific DOM elements) it would be initialized like this: $('.tooltipClass').myP ...

Can Angular JS handle Object Logging?

Exploring the possibility of using Angular JS with MVC 5.0, I am looking for a way to log the complete class Object into a database whenever an Insert/Edit/Delete operation is performed. Is there a library available in Angular JS that can help serialize ...

Step-by-step guide on using nodemon on a web hosting server

I am currently designing a website that includes a login form and I am in the process of uploading it to a web hosting service In order to activate my login form, I have to use node index Is there a way to change the destination of this tag: <li class ...