Shai UI
Shai UI

Reputation: 51928

How to use css3 translate to move to an absolute position

How would I use css3 to translate to an absolute position. It seems that it always translates relative to my current location (where my current location is 0,0), but I'd rather it translate it relative to the screen, so that the upper left portion of the screen is 0,0.

http://jsbin.com/qujabe/1/edit

For example, I'd like to be able to move the red box (when clicked) onto the green box using the green box's offset() position. (note: I want to do this with css3 translate not left/top absolute coordinates)

Upvotes: 0

Views: 385

Answers (2)

Shai UI
Shai UI

Reputation: 51928

Here's how I ended up doing it.

function translateToAbsolute(sel, x, y, dur)
{
    var offset = $(sel).offset();

    var newX = -offset.left+x;
    var newY = -offset.top+y;

    $(sel).css('transition','all '+dur+' ease');
    $(sel).css('transform','translate('+newX+'px,'+newY+'px)');
}

Upvotes: 0

ctwheels
ctwheels

Reputation: 22817

Here, add this before your function "flyToBox2()"

var myVarW = $("#box1").offset().left;
var myVarH = $("#box1").offset().top;

and change

translate('#box1',30,30, '1s');

to

translate('#box1',-myVarW+30,-myVarH+30, '1s');

Unfortunately jsfiddle is down at the moment, otherwise I would include a link to a fiddle as well

Upvotes: 1

Related Questions