Home > database >  How do I make two identical classes work differently with the same javascript function?
How do I make two identical classes work differently with the same javascript function?

Time:10-04

I want to make these two circles move differently (they acquire the same direction while moving) with the same javascript function, but I am quite new using javascript and do not know how to make it.

I do not know how to make javascript differ between the same classes in html to get the same function but work differently depending on their specific class. My ideal code would make the two circles move randomly but in independent direction from one to another.

<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  style="top:18%;left:15%">
        <a href="childs_html/aa.html" >aa</a>
    </div>
    <div  style="top:58%;left:18%">
        <a href="childs_html/bb.html" >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;
    /* border-style:solid; */
  }
  
  .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();        
      });

};

Thank you very much!

CodePudding user response:

To target circle aa:

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

To target circle bb:

$('.circle.bb').animate({ top: newpos[0], left: newpos[1] }, speed, function(){
     // Animation for circle bb 
     animation_bb();      
});
  • Related