Switch up the placement of the boxes by moving them in different directions, such as

I've been attempting to recreate the button movement demonstrated in this link , but I'm having trouble achieving it. Using CSS animation, I can make the buttons move in a straight line, here's what I have so far:

<div id="box" style='width:200px;height:200px;border:1px solid black;'>

    <button id="one" type="button">Button1</button>
    <button id="two" type="button">Button2</button>
    <button id="three" type="button">Button3</button>

<style>

button{
-webkit-appearance:none;width:40px;height:40px;padding: 0;text-align: center;vertical-align: middle;border: 1px solid red;font-size:10px;font-weight:bold;
}

#one, #two, #three
{
position:relative;

}
#one
{
-webkit-animation:levelseven 16s infinite;
    -webkit-animation-direction:alternate;

}

#two
{
animation-direction:alternate;

/* Safari and Chrome */
-webkit-animation:levelseven_1 8s infinite;

}

#three
{
animation-direction:alternate;

/* Safari and Chrome */
-webkit-animation:levelseven_2 10s infinite;

}


@-webkit-keyframes levelseven /* Safari and Chrome */
{
0%   { left:0px; top:0px;}
25%  { left:200px; top:0px;}
50%  { left:100px; top:200px;}
75%  { left:150px; top:50px;}
100% {background:cyan; left:0px; top:0px;}
}

@-webkit-keyframes levelseven_1 /* Safari and Chrome */
{
0%   { left:0px; top:0px;}
50%  {background:darkgoldenrod; left:0px; top:200px;}
100% { left:0px; top:0px;}
  }


@-webkit-keyframes levelseven_2 /* Safari and Chrome */
{
0%   { left:0px; top:0px;}
50%  {left:200px; top:0px;}
100% {left:0px; top:0px;}
}

</style>

Here's My JsFiddle

Answer №1

Here is an example you can use to create something similar: Fiddle

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

function makeNewPosition(){

    // Get viewport dimensions (subtract the dimension 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;

}

Make sure to check out the updated fiddle for more details.

Updated Fiddle

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

ajax is providing identical data when called too frequently

Using my barcode scanner triggers the function below, but scanning multiple barcodes quickly results in duplicate data being processed. The issue seems to be related to the async setting - when it's false, the process slows down significantly. Is the ...

The Bing map control fails to adhere to the div element

After visiting , I successfully generated a map using the following HTML code: <div class="fluid-row" style="height:300px;"> <div class="span12"> <div id="prdmap" class="map"> </div> </div> Here is the accompanying J ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Guide on saving the token in local storage or cookies to grant access to specific web pages for users

Currently, I am in the process of developing an authentication system using Node.js, MySQL, and Express. Initially, I focused on saving and verifying user credentials in the database. Recently, I incorporated JWT (JSON Web Token) into the system. My next s ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

What is the best way to enforce a required selection from one of the toggle buttons in a React form?

Is there a way to require the user to click one of the toggle buttons in a react form? I need to display an error message if the user submits the form without selecting a button. I tried using the "required" attribute in the form but it didn't work. H ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Error Encountered with Nested Angular Material Tabs

Is there a way to prevent changes made to the upper tab in md-align-tabs attribute from affecting the inner tab when one tab is nested inside another using md-tabs? If so, how can I achieve this? <md-content layout="column" layout-fill> <md-ta ...

Accessing data attributes using AngularJS

Trying to extract the data attribute from the following code: <button ng-click="EditPlayer(name, position, number, age)" id="btnEdit" class="btn btn-successes" data-playerid="{{player.id}}">Save</button> Within my angular controller: $scope. ...

Executing a function when an item is dragged in jQuery UI sortable

I have a "draggable" block and a "sortable" block. What I am trying to achieve is to trigger an action through jQuery when I drag an item from the "sortable" block. Below is the JavaScript code I am currently using: $(".sortableList").sortable({ }); ...

The navbar links in Bootstrap 4 may be hidden, but the navbar brand still remains visible

I have implemented this code for my website's navbar, however, upon running it, I noticed that the navigation links are not visible. The navbar brand name "test" appears correctly, but the other links seem to be hidden. Does anyone have any insights o ...

Initiate a $digest cycle externally

How can I ensure that $digest triggers when calling methods from outside Angular in an application where code is loaded and eval'd at runtime? Considering that these methods may also be called from within Angular, would it be better to expose a separa ...

Tips for converting a raw SQL query to Knex syntax

Recently delving into the world of development, I've come across knex for the first time. Issue: I have a raw SQL query that is functioning correctly. Now, I'm attempting to utilize knex for this query. To better understand how things operate, I ...

Validating with jQuery: ensuring a field is either zero or a multiple of 20

I need to use the jQuery validation plugin to ensure that a field is either 0 or a multiple of 20 (0, 20, 40, 60, ...). Can anyone provide guidance on how to accomplish this? ...

Is it possible to use Gulp.js to serve src files without browserSync enabled?

Started a fresh project using Yeoman Gulp-Angular generator. I grasp the concept of BrowserSync, but I simply cannot fathom why anyone would put up with their network requests being overwhelmed by it: I am inclined to eliminate BrowserSync from my projec ...

What is the method for including a TabIndex property in a JSON file?

https://i.sstatic.net/ISi72.png I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

How to transform a nested string into a JSON object using JavaScript

I am trying to manipulate a nested query string in JavaScript. The string looks like this: var str = "( ( Sentence starts with any of null AND Sentence starts with any of null ) AND Sentence starts with any of null )" I want to split the string at the &a ...

Having issues with json_decode not functioning correctly after using JSON stringify

After encoding a JavaScript array into JSON and posting it to PHP, I encountered an issue. Before posting the data, when I checked a value in the array using console.log(selection[878][2824]), I received the expected result. However, after encoding the var ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...