waxical
waxical

Reputation: 3896

jQuery - Placing a div with offset, then placing it again = different results

I'm placing a div, by using another div id as a reference on the page (to make sure that it appears where I want it to). The code is as follows:-

$('#' + contentDiv).offset({top:($('#' + placementID).offset().top), left: ($('#' + placementID).offset().left)});

The problem is, that though the placementID offset figures are the same each time. Whenever I call this again, it seems to double and put a new left offset that is the the same amount on-top of the previous offset.

E.g. I call a function on a click and say, place this div next to this placement div please. It does it. User then exits and then does another click and the same function is used to place another div next to the same placement div. It does it, but instead of placing it in the same position as last time, seems to reference the position of last time as the 0 point and adds the left amount to that. Meaning the div is placed double distance away now.

Please note; I have consoled out the placement box top and left dimensions and it hasn't changed after each time.

Not sure what's going on.

Upvotes: 2

Views: 1236

Answers (4)

bm2u
bm2u

Reputation: 1

Reset your properties before setting the desired offset-value with (e. g.)

$(this).css('top', '').offset({top: desiredTopOffset});

Upvotes: 0

Levon
Levon

Reputation: 159

According to http://bugs.jqueryui.com/ticket/6868 The element must be visible before calling .position(). after changing my code to show the element before calling offet() it worked like a charm.

Upvotes: 0

waxical
waxical

Reputation: 3896

If someone runs into this, I've managed to solve the problem very simply... by using css instead of offset. I.e.

$('#contentDiv').css({top:placeTop,left:placeLeft});

Upvotes: 4

Jason
Jason

Reputation: 11615

Im guessing that when you change the offset of $('#' + contentDiv) it affects the offset of your $('#' + placementID) that you subsequently call.

Say you have 3 placement Id's #1,#2 and #3.

With offsets #1: 0,0 #2: 0,100 and #3: 0,200.

Then you set #contentDiv's offest to #1's offset.

Now, #contentDiv's offset is 0,100. This makes your placement offsets #1: 0,100 #2: 0,200 and #3: 0,300 respectively now. Which is probably what is throwing you off.

Upvotes: 0

Related Questions