Lâm Ánh
Lâm Ánh

Reputation: 51

Change div position by time

I want to change my div's top and left position every 200ms, why doesn't this code work?

$(document).ready(function(){
    setInterval(function () {
        //$('#quatao').css("top", "+=20"); it's work!!!!
        if (parseInt($("#quatao").css("top"),10) < 350) { 
             $("#quatao").css("top", "+=20", "left", "-=30");
         }
         else if (parseInt($("#quatao").css("top"),10) > 500) {
             $("#quatao").css("top", "-=20", "left", "+=30");
         }
    }, 200);
});

Upvotes: 0

Views: 104

Answers (2)

Victor Can&#244;
Victor Can&#244;

Reputation: 543

You must have initially set the top position on CSS, else '$("#quatao").css("top")' should return 'auto' instead of a number.

It could be simple as:

<div id="quatao" style="top:0px;left:0px"></div>

Check if this is what you're looking for: http://jsfiddle.net/8g1Lzr5c/1/

Upvotes: 0

Gustav
Gustav

Reputation: 1341

From what I can see just by looking at the code, you should use objects instead of a comma list inside of the $("...").css calls.

$("#quatao").css({"top": "+=20", "left": "-=30"});

$("#quatao").css({"top": "-=20", "left": "+=30"});

Note, when only one value is to be changed, comma separation works, but for two or more values, a json-object is needed.

Check out different usages for .css here

Upvotes: 2

Related Questions