Lucas Li
Lucas Li

Reputation: 13

How can I animate with .class in JQuery?

I can animate the #ID Div tag to move around, but I cant call the .class Div Tag to move. How can I do that correctly ?

.myClass {
                width: 40px; height: 40px;float:left;padding: 1px; margin:3px; 
                position:absolute; left:50px; top:60px; background:blue; color:white;
          }

In the HTML:

<div class="myClass">Insert image2</div>
<div class="myClass"><img src="jef-frog.gif"width="50">DIV myCLASS</img></div>

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

            /* Generate some random starting position */
            var startmyClassX = randomRange(50,100);
            var startmyClassY = randomRange(50,100);

var item2 = $(".myClass"),cycle1;

function runItem2() {
                /* Set a the starting position to be random by editing the css */
                $(".myClass").css("left", startItem2X+"px");
                $(".myClass").css("top", startItem2Y+"px");
                $(".myClass").svg(onLoad);

                (cycle2 = function() {
                 var m = randomRange(50,100);
                 var n = randomRange(75,150);
                 myClass.animate({top:'+='+m, left:'+='+n},2000);
                 myClass.animate({left:'-='+n},2000);
                 myClass.animate({left:'+='+n, top:'-='+n},2000);
                 myClass.animate({left:'-='+n},2000)
                 myClass.animate({top:'+='+m},2000,cycle2)

                 })();

            }

runItem2();

Anyone can help to solve this issue? Thanks

Upvotes: 0

Views: 253

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

You have a variable var item2 = $(".myClass"), but then later in your code where you should be using item2 you use myClass:

myClass.animate({top:'+='+m, left:'+='+n},2000);
...
myClass.animate({top:'+='+m},2000,cycle2)

Either rename the variable to myClass or change the later code to use item2. (You've also declared a variable cycle1 and then later used cycle2.)

Note that the callback you provide to the .animate() method will be called once per element being animated, so with $(".myClass") matching two elements you're going to be doubling the number the animations each time you restart the cycle.

Note also that in your demo you've got two things moving independently, but if you animate all elements with the same class from that one animation function then all the elements will move the same way.

Upvotes: 1

Related Questions