views:

146

answers:

4

Hey all,

Quick question: It's kind of tough to describe so let me just show an example.

Is there anyway to do this: (I'm using jQuery but this is a general javascript question)

$('div.element').offset().x;

$('div.element').offset() by itself will return {'x' : 30, 'y' : 180}, so I'm just wondering if there is any compact way of doing this without creating an extra variable.

Thanks! Matt

A: 

It will always create the object. I think you mean .top or .left instead of x/y?

>>> $('#jq-header').offset().left // 177.5
var coords = $('#jq-header').offset()
coords.left // 177.5
coords.top // 0
alert($('body').offset().left) // 0

http://docs.jquery.com/CSS/offset

meder
A: 

Short answer: Yes, absolutely, just as you wrote. What's not working?

deceze
A: 

Apparently, you can do the exact thing you said: $('div.element').offset().x;.

Javier Badia
+4  A: 

As you said, you can absolutely use this:

$('div.element').offset().left

OR

$('div.element').offset().top

Please note that jQuery's offset() returns { left: 30, top: 180 } not an x/y pair like you said.

Darko Z
thanks for the correction Shog :)
Darko Z
Ahhh. That's what tripped me up. Silly me - not looking at the documentation. Thanks man.
Matt