"Creating dynamic movement for a collection of layered images through asynchronous operations in JavaScript: A step

I have a collection of 10 shapes that together form an intricate square image, depicted in the diagram below. My goal is to animate each shape by utilizing the output of a periodic function such as sine, which would dynamically respond to the user's mouse position. Each shape should move in a unique pattern influenced by different frequencies and periods, resulting in a captivating visual effect where the shapes constantly shift relative to one another as the user hovers over them.

https://i.sstatic.net/TMghS.png

Currently, I have succeeded in animating a single shape with the following code:

$(document).mousemove(function(e){
        var track = function(ampl, freq) {
        return {
            x   : ampl * Math.sin(freq*e.pageX),
            y   : ampl*1.6 * Math.sin(freq*e.pageY)
        };
    }

        var current = track(10, 0.05);
    $("#image").css({left:current.x, top:current.y});

});

My challenge now lies in extending this functionality to apply to the other 9 shapes showcased in this jsfiddle. How can I achieve this integration?

Answer №1

To achieve a similar effect, I recommend following this approach: http://jsfiddle.net/jfhk8bye/

track = function(ampl, freq, pageX, pageY) {
    return {
        x   : ampl * Math.sin(freq*pageX),
        y   : ampl*1.6 * Math.sin(freq*pageY)
    };
}
$imgs = $('img.image')
$(document).mousemove(function(e)
{
    $imgs.each(function()
  {
    var $img = $(this);
    var current = track($img.data('ampl'), $img.data('freq'), e.pageX, e.pageY);
    console.log(current);
    $img.css({left:current.x, top:current.y});
  });
});

The changes made include:

  • Converted image IDs to classes and updated corresponding CSS accordingly.
  • Added data attributes to store frequencies and amplitudes for better HTML control.
  • Optimized and adjusted the JavaScript code as needed.

Answer №2

Perhaps a solution could look something similar to this: http://jsfiddle.net/g7Lpnw5b/

Substitute your id's with class names, since multiple elements cannot have the same identifier, then loop through the elements to relocate them to different positions. You may need to adjust the parameters of the track function in order to achieve the desired movement of the shapes.

Answer №3

It's accurate what @charsi mentioned.

For obtaining a distinct index value and applying it in the functions sin and cos, make sure to utilize $.each(index,el).

Check out this demonstration

function move(amplification, frequency, ind,x_coord,y_coord) {
  return {
    x   : amplification * Math.sin(frequency*x_coord + ind),
    y   : amplification*1.6 * Math.sin(frequency*y_coord + ind)
  };
}

$(document).mousemove(function(e){
    $(".image").each(function(ind,el){
           var current = move(5, 0.05, ind, e.pageX, e.pageY);
       $(this).css({left:current.x, top:current.y});
    });
});

Update: Ensure that the function is placed outside of the mousemove event

Answer №4

Each image must have a unique identifier to avoid jQuery only affecting the first one found. Assign different ids to each image and include them in the list individually. Be sure to update the current value before each image to prevent alignment issues.

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

The Establishment Embrace of AJAX Interaction

I've been working on developing a check user system to prevent duplicates. The function below is successfully returning true or false, but for some reason it's not triggering the error display for the error class system. JavaScript $(document). ...

Enable the modal window to be scrollable

I've been struggling with configuring my modal to allow scrolling when the content overflows. I attempted to add "overflow: auto" to the modal, but it didn't seem to do the trick. It's important to note that I am not utilizing Bootstrap. One ...

AngularJS Array Indexing

$scope.ptArray={m1 : $scope.somevalue1, m2 : $scope.somevalue2, m3 : $scope.somevalue3}; $scope.errMsg={m1 : 'msg1', m2 : 'msg2', m3 : 'msg3'}; if($scope.ptA ...

Permanently remove the span tag and any associated text from the HTML document

Currently, I am working on a project that involves numerous page numbers marked using the span class. Below is an example of this markup: <p>Cillacepro di to tem endelias eaquunto maximint eostrum eos dolorit et laboria estiati buscia ditiatiis il ...

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

Top approach for creating/previewing a website using PHP, CSS, and MYSQL

When creating a website that will eventually be hosted on a remote server, what is the most effective way to code and test? Here are some examples of what I mean: - Develop locally on your computer and access files from there. Should libraries and databa ...

The custom tooltips feature in Google linecharts will function properly only when the focus target is set to category

I am currently using PHP, MongoDB, and JavaScript to develop my Google Charts Line charts. In PHP, I have designated one column as the tooltip role, positioned as the last but one column. The default tooltip displays the X-axis (Date) and Y-axis (Value), b ...

Pagination in the jQuery datatables plugin is not functioning as expected

Help Needed I am using the datatables jQuery Plugin to display a table, but I am facing an issue where all entries are shown without any pagination. Can someone please assist me with this problem? Below is my index.cshtml code: @{ Layout = null; } & ...

Is it possible to transmit image form data to a PHP function in order to facilitate uploading?

Trying to implement image upload using both jquery and PHP: Here is the HTML code snippet: <form id="form-photo" enctype="multipart/form-data">< <span class="btn btn-small fileinput-button"> <span>Add Photo</span> < ...

The Django framework does not apply color to the Bootstrap Navbar as expected

I'm currently working on building an E-Commerce Website using Django. I have implemented a Bootstrap navbar, but the CSS styles that I obtained from this source are not functioning properly when placed within the {%block css %} tag. I have attached t ...

Hierarchy segment for CSS selection

I have a rather unique query. How can I create a selector that targets a specific part of the hierarchy based on classes? For instance, I'd like to select something like: <node class="start-selection"> <node> <n ...

In what specific format does this plugin expect the callback string to be encoded as? (jquery-ui-multisearch)

Currently, I'm working with a plugin named "Jquery-ui-multisearch" that provides an autocompletion feature in an input field based on either a provided array or an external source (such as ajax/api, etc). You can find more information about this plugi ...

Storing user browsing history and showcasing a randomly chosen page

Currently in the process of creating a website where various pages will be dedicated to showcasing videos. I envision an innovative feature where the site will continue to play random videos successively without repetition, ensuring that users have a uniq ...

PHP - Real-time form validation?

Looking for advice on implementing real-time feedback for a registration form on my website. Is there a way to automatically notify users if their chosen username is already taken without requiring them to submit the form first? Thanks in advance. ...

Spending additional time retrieving data with DataTables

I have implemented DataTables to paginate my results. Here is the code I am currently using: $('#datatable_paging').dataTable( { "sPaginationType": "full_numbers", "bLengthChange": false, ...

Don't proceed until the condition is satisfied with Selenium-Webdriver

As I delve into creating additional conditions with selenium-webdriver, the concept of promises and callbacks is still somewhat foggy to me. Thankfully, forums like Stack Overflow have been instrumental in improving my understanding. One area that remains ...

Retrieve information from cache following the completion of an ajax request

Recently, I implemented a popup menu that dynamically loads subcategories using AJAX when a category is clicked. For example, there are 10 main categories each with multiple subcategory lists that are loaded via AJAX in the popup. However, I noticed that w ...

Utilize PHP to extract data from a SQL database and dynamically create li elements within a ul container for every row retrieved

I am completely new to this and trying to figure things out. My main aim is to design a dropdown menu within my navigation bar that displays different themes, allowing users to change the color theme of the page by clicking on an element. I have organize ...

Is it possible to compare data from two separate firestore collections before making updates to documents within each of them?

I've been utilizing firestore, cloud functions, and the Admin SDK to construct a blog/forum platform. In this setup, there are two main collections: forumPosts and forumComments. Each comment in the forumComments collection is linked to its parent pos ...

Using jQuery to switch classes when the input is invalid

Just getting started with learning jquery and experimenting with form validation in HTML. My goal is to have input fields turn red if they are empty, so I initially set all inputs under the class "valid". When a field is submitted empty, I want jQuery to ...