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 could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Why is my jstree create_node event not being triggered even though the node is successfully created?

Even though I am able to successfully create the node, the event is not firing as expected. There are no reported errors in Firefox. What could be causing this issue... $("#treeFile1").jstree("create", null, "outside", { "attr" : { "rel" : "folder" } ...

Customizing Thickness for Tab Labels in MUI 5

I have been trying to adjust the thickness of the label inside a tab using MUI 5, but so far I haven't had success. Here is what I have attempted: interface TabPanelProps { children?: React.ReactNode; index: number; value: number; } funct ...

The angularJS ternary expression is not considered valid

{{var.a != "N/A" ? "<a ng-href='myapp://find?name="+var.a+"'>"+'var.a'+"</a>" :var.a}} The ternary operator I have used in this Angularjs format does not seem to be working correctly. In the view, the ternary result is not ...

Send information using AJAX within a .NET integrated browser

In our current setup, we utilize a .NET embedded browser to showcase an HTML page that is generated by applying an XSLT file to an XML file using .NET. This process results in HTML content displayed within the embedded browser through the DocumentText prop ...

How can you display '<>' characters in a QLabel and set text accordingly?

In my PySide2 (similar to PyQt5) project, I am facing an issue with setting text in a QLabel that includes characters like '<' and '>'. These characters seem to disappear because they are used for font modifications. I have tried escapi ...

Issue with custom leaflet divIcon not maintaining fixed marker position during zoom levels

After creating a custom marker for leaflet maps, I noticed that it shifts position drastically when zooming in and out of the map. Despite trying to adjust anchor points and positions, the issue persists. I have provided the code below in hopes that someon ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

Creating dropdown options with JSON and Angular

This dilemma has been causing me no end of distress. I am trying to figure out how to populate options for a select tag from a JSON object using Angular. Here is a snippet of the code: <select id="cargo" ng-model="cargo.values.cargoList"> <op ...

Tips for eliminating checkboxes from a form

function addCheckbox(){ var labels = document.form1.getElementsByTagName('label'); var lastLabel = labels[labels.length-1]; var newLabel = document.createElement('label'); newLabel.appendChild(Checkbox(labels.length)); ...

Tips for positioning the footer at the bottom of the page

During the process of constructing a new website, I included a footer that is neatly positioned at the bottom of my screen. However, I noticed that on pages with minimal content, the footer does not remain fixed at the bottom: In order to ensure that the ...

Is there a way to adjust the background hues of a React component when a click event is triggered?

Currently, I have 3 React components that each consist of a div element. When I click on one component, I want to change its background color to black. If I then select another component, the previously selected component should return to its normal back ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

Extract a value from a json document

Hey there! I'm looking to create an unwhitelist command. When a user is mentioned or their ID is provided, I want it to be removed from the JSON file without checking if the ID exists. Do you have any suggestions on how to accomplish this? Here is my ...

Once more baffled by the nested boxes, this iteration adorned in vibrant hues and trimmed with a striking border

In a previous inquiry, I sought advice on centering one box within another. However, my attempts this time around have led to some peculiar results. I experimented with two different code variations- one involving a background color and the other utilizing ...

How to implement responsive CSS in Laravel 4

It has come to my attention that in Laravel 4, you can load CSS and scripts using the following method: {{ HTML::style('css/style.css'); }} Which will result in: <link media="all" type="text/css" rel="stylesheet" href="http://localhost/cupc ...

Using an ellipsis in a hyperlink within a list item conceals the bullet points of the list

When I apply an ellipsis to the text within a list element that has disc bullet points, it hides the bullet point itself. I discovered that applying overflow: hidden to the list will also hide the bullet point. Moving this rule to the anchor within the li ...

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...