What is the best way to differentiate the behavior of two identical classes using a single JavaScript function?

Can someone help me figure out how to make two circles move differently with the same JavaScript function? I'm new to JavaScript and struggling to differentiate between classes in HTML to achieve this. My goal is to have each circle move randomly and independently from the other.

I want the two circles to have unique movement patterns even though they share the same function. Any suggestions on how to approach this would be greatly appreciated.

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/stylesheet.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
    
<body>
    <div class="wrapper" style="top:18%;left:15%">
        <a href="childs_html/aa.html" class="circle aa">aa</a>
    </div>
    <div class="wrapper" style="top:58%;left:18%">
        <a href="childs_html/bb.html" class="circle bb">bb</a>
    </div>
    <script src="javascript/circle_movement.js"></script>
</body>
body {
    overflow: hidden;
    margin: auto;
    width: 640px; 
    padding: 50px;    
}

.wrapper {
    position:absolute;
    height:200px; width:200px;
}

.circle {
    position:relative;
    height:100px; width:100px;
    margin-top:50px;margin-left:50px;
    border-radius:50%;
    border-style:solid;
}
$(document).ready(function(){
    animation();
}

function randomNumber(min, max) { 
    return Math.floor(Math.random() * (max - min) + min);
} 

function new_position() {
    var newt = randomNumber(-50,50);
    var newl = randomNumber(-50,50);

    return [newt, newl]
}

function animation(){
    var newpos = new_position();
    var speed = 2000;

    $('.circle').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
        animation();        
    });
};

Your assistance is highly appreciated!

Answer №1

When aiming for circle aa:

$('.circle.aa').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Executing the animation for circle aa
     execute_aa();      
});

When targeting circle bb:

$('.circle.bb').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Performing the animation for circle bb 
     perform_bb();      
});

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

Avoiding unnecessary re-renders of a parent component caused by a child component

I'm facing rendering problems and would greatly appreciate any assistance. I attempted to use useMemo and useCallback, but it resulted in the checkbox breaking. Within a component, I am displaying information from an object. Let's consider the fo ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

Having Trouble Accessing Full Website Source Code with Selenium and Python

Currently, I am attempting to extract data from the following website: https://script.google.com/a/macros/cprindia.org/s/AKfycbzgfCVNciFRpcpo8P7joP1wTeymj9haAQnNEkNJJ2fQ4FBXEco/exec Utilizing selenium and python for this task, I am encountering a challe ...

How to set a default checked value in a custom DropDownList in AngularJS?

I have created a bespoke DropDownList in my HTML code. I'm looking for guidance on how to set one of the options as default within the following scenario: <div class="dropdownlistheader" ng-click="toggle('subdiv','item')"> ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

Using jQuery, you can create and add an element to the page when a user clicks

Currently, my webpage contains numerous anchor tags that link to various video files, along with a single div element: <a href="http://www.example.com/example-1.mkv" class="video">1</a> <a href="http://www.example.com/example-2.mkv" class=" ...

Can we display the chosen form values before submitting?

Want to implement a confirmation message for users before submitting their form using onClick="return confirm('are you sure ?')". The basic form structure is as follows: <form> <Select name='val[]' class='select'> ...

How can I prevent media controls from appearing in fullscreen mode on Microsoft Edge using CSS?

My video code allows for switching the video into fullscreen mode using custom controls. Here's how it looks: fullScreenButton.addEventListener("click", function() { if (video.requestFullscreen) { video.videoContainer.r ...

Who is responsible for triggering a PostBack?

I am trying to identify the control that triggers a page PostBack within the Page_Load event, as there are multiple controls on my page. ...

The v-model in Vue does not function correctly when used with a single index within an array

I am encountering a situation with a series of input fields, including a checkbox and a dropdown button in each row. Additionally, there is a button to add a new row of inputs. When the checkbox is checked, it should disable the dropdown menu and make it ...

How can I effectively retrieve the JWT in a node environment?

I've successfully set up JWT authentication using Node.js. After the user signs in, Node.js generates a JWT and sends it back to be stored in the localStorage. However, I've encountered an issue when trying to access this token within the express ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...

Save hyperlinks in a storage system

I need to store an article in a MongoDB database, and some words within the article should be clickable links leading to other pages. However, when I display the article using an EJS template, the anchor tags I added while writing the article appear as pl ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

Determine the size of a file in either megabytes or kiloby

I need to determine the size of a file in either megabytes if the value is greater than 1024 or kilobytes if less than 1024. $(document).ready(function() { $('input[type="file"]').change(function(event) { var _size = this.files[0].si ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

Use JavaScript to create a new window and load the HTML content from an external URL

Just starting out with HTML and Javascript I'm trying to use JavaScript to open a window and load content from an external source. I attempted using document.write(), but it only works when I hardcode the HTML as input. Any suggestions on how to get ...

Collaborative session sharing between two node applications through Single Sign-On (SSO

I currently have a website created with express and node.js. I need to add a nodebb forum to this website, which is a separate node application. Both the main site and the forum use Facebook login, but users have to log in separately using the same Faceboo ...