Creating smooth and natural movement of a div element using Javascript (rotating and moving)

After struggling to use jquery plugins for smooth motion with the div elements I'm working on, I've decided it's time to seek some assistance.

I have a group of div elements that all share a class and I want them to move around the screen continuously (similar to this fiddle I came across). The techniques used in that fiddle work well for Raphael vector graphics but not so much for CSS elements (I did attempt it being the noob that I am).

The challenging part is this - I want each element to rotate so that their "top" always faces the direction of motion. This aspect is proving to be quite difficult for me (especially since I haven't done trigonometry since high school).

So, how can I achieve the rotation and translation of a div element as described? Since I already use jquery elsewhere on the page, I'd prefer to stick to jquery without adding any other frameworks.

As a side note, I tried using move.js, but it seems to only support absolute translations, not relative ones. This results in my element moving during the first interval but then staying in place during subsequent intervals. With random translations, it just bounces around within a fixed box. I am currently experimenting with minimit Anima, yet the outcome appears to be similar. I use the jquery .each() method to move each element separately (which works relatively well). At present, I am trying to create a vector (angle and distance) and apply some trigonometry to derive (relative) translation coordinates.

:edit: Check out this fiddle containing the translation/rotation code I've been working on, utilizing CSS3 transforms and jquery's .animate(). Unfortunately, I haven't had any success yet, and the lack of progress is disheartening. Note: I'm only using the webkit transform at present; cross-browser compatibility will be addressed once I get it functioning.

:edit: Removed the full code - the snippet from the fiddle should suffice :/edit:

setInterval('moveMoth()', 100);
var moveX, moveY, moveH, angle;
var i = 0;

function moveMoth() {
    $(".mothwrap").each(function () {
        if (angle) {
            angle = ran(-15, 15) + angle;
        } else {
            angle = ran(-15, 15);
        }
        moveH = ran(20, 60);
        moveX = (Math.cos(angle * Math.PI / 180)) * moveH;
        moveY = (Math.sin(angle * Math.PI / 180)) * moveH;
        $(this).children('.mothdiv').css({
            WebkitTransform: 'rotate(' + angle + 'deg)'
        });
        $(this).animate({
            left: '+=' + moveX,
            top: '+=' + moveY
        }, 500);
        $("#mothbox").append("Interval");
    });
}

Answer №1

Finally figured it out! I was initially confused because the element I wanted to move was moving sideways instead of forwards. Focusing on getting the movement right for one before adding more really helped.

Here's my current code. It's not perfect yet, but it's good enough for now :)

function moveButterfly() {
    // Adding this comment for troubleshooting purposes.
    // If the script is running correctly, this message should appear on the page
    //$("#butterflybox").append("Interval");
    
    var moveX, moveY, moveH, angle, borderL, borderR, borderT, borderB, posLeft, posTop;
    
    var position = pageCell.position();
    borderL = position.left;
    borderT = position.top;
    borderR = parseInt(pageCell.width());
    borderB = parseInt(pageCell.height());
    
    $(".butterflywrap").each(function (index,element) {
        var me = $(this);
        
        angle = parseInt(element.getAttribute("data-angle"));
        
        if (angle) {
            angle = parseInt(ran(-15, 15)) + angle;
        } else {
            angle = parseInt(ran(0, 360));
        }
        
        posTop = parseInt(me.css("top"));
        posLeft = parseInt(me.css("left"));
        
        if (posLeft < borderL) { angle = 0;}
        if (posLeft > borderR) { angle = 180;}
        if (posTop < borderT) { angle = 90;}
        if (posTop > borderB) { angle = 270;}
        
        if (angle < 0) { angle += 360;}
        if (angle > 360) { angle -= 360;}
        
        element.setAttribute("data-angle", angle);
        moveH = ran(2, 6);
        moveX = parseInt((Math.cos(angle * (Math.PI / 180))) * moveH);
        moveY = parseInt((Math.sin(angle * (Math.PI / 180))) * moveH);
        
        me.children('.butterflydiv').css({
            '-webkit-transform':'rotate('+angle+'deg)',
            '-moz-transform':'rotate('+angle+'deg)',
            '-ms-transform':'rotate('+angle+'deg)',
            '-o-transform':'rotate('+angle+'deg)',  
            '-ms-transform':'rotate('+angle+'deg)',
            'filter':'progid:DXImageTransform.Microsoft.BasicImage(rotation='+angle+')'
        });
        
        me.css({
            top: '+=' + moveY + 'px;'
        });
        
        me.css({
            left: '+=' + moveX + 'px;'
        });
    });
}

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

What is the best way to enlarge a navbar from the top using Bootstrap 5?

I have a button labeled "MENU" at the top and a logo image below it. Currently, the menu expands from the bottom of the button. I would like it to expand from the top instead, and when the menu is expanded, the button should be under the navigation list, n ...

Is it possible to display a pdf.js page as actual HTML elements rather than as canvas or SVG?

I am in the process of creating a user-friendly mobile interface for pdf reading. However, I want to incorporate more advanced features by developing my own pdf reader instead of relying on the pdf.js team's viewer. Is there a method available to rend ...

PHP: implementing several forms on a single webpage

In my current situation, I need to display forms that resemble an Excel sheet with a submit button next to each row. When the submit button is clicked, the data is saved for that specific row, the row is disabled, and the focus automatically moves to the n ...

Having trouble getting the jQuery click event to work on iPhone browsers? Despite already trying the cursor:pointer; method

I am facing an issue with setting a click event on anchor tags in my WordPress site. Surprisingly, the event works perfectly fine on all of my devices including PC, Android phone, and tablet except for my iPhone. Despite trying to set the 'Cursor&apo ...

What is the best way to save JSON data within HTML elements?

I want to enhance my FAQ by making it easily editable. Currently, the content can only be edited in the HTML file. I am looking to load all the information from a JSON file so that any changes or additions to questions and answers can be made directly in t ...

Issue: Unable to access 'filter' property of null object

I've been working on a small react dropdown task and it's running smoothly in Google Chrome. However, I encountered an error when testing it on MS Explorer. Even after deploying it on a live server, the issue persisted. The specific error message ...

Using TypeScript, implement a function that is called when a React checkbox's state changes to true

Currently, I am experimenting with the react feature called onChange. My goal is to update local data by adding a value when a checkbox is selected. Conversely, when the checkbox is unselected, I just want to display the original data. However, I find that ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

The event.pageY position consistently reflects the laptop screen size rather than the exact position where the click occurred

My webpage is scrollable, but the event.pageY position always corresponds to my screen size. Even when scrolling down and clicking near the top of the screen, it registers as 50px. I am currently utilizing event.pageY While this functions correctly on a ...

Transforming Django models into JSON format to be utilized as a JavaScript object

Looking to retrieve model data as an object in Javascript, I've been using the following approach in my Django view: var data = {{ data|safe }}; Here is how my view is set up: context = { 'data': { 'model1': serializ ...

Why is my JQuery UI droppable accept condition failing to work?

After scouring the internet for hours, I'm still stuck and can't seem to figure out what's wrong with my code: Here's the HTML snippet: <ul style="list-style:none;cursor:default;"> <li>uuu</li> <li>aaa& ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

No translation or compiling of SCSS/SASS to CSS available

As a beginner Sass user, I am working on mastering the SMACSS hierarchy and incorporating it into my project using Brackets. However, I have encountered an issue with mapping the main.scss file to the main.css file even though it compiles successfully via ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

The connection between an HTML form and PHP is not being established

variable-passing.php `<form method="post" action="variable-catching.php"> <input type="text" name="name1"/><br/> <input type="text" name="name2"/><br/> <input type="text" name="name3"/><br/> <input type="te ...

Uncertainties surrounding the complexity of this multi-stage form

Exploring this multi-step form I have a couple of questions: 1) Is there a way to transfer the value from the first step to the second step of the form? 2) How can I ensure that the datepicker value is not empty (to prevent user progress in the firs ...

Minimize the width to display a scrollbar

Check out this page: where you'll find the same code snippet displayed twice - once through GitHub Gist embedding and the second using Jekyll's internal syntax highlighter Rouge. I'm currently working on styling the second code snippet to m ...