Scott
Scott

Reputation: 5369

Change Origin of Coordinates in Javascript

How can I possibly change Javascript's origin? For example, if I were to call offsetTop on a div, it's really tell me how far it is from the origin. Javascript's origin is at the top left of the page, but how can I move that?

I want to make it at the bottom left.

Upvotes: 0

Views: 1186

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

Your information about offsetTop is incorrect. From MDC:

offsetTop returns the distance of the current element relative to the top of the offsetParent node.

You cannot "move" the origin in the way you are thinking, though you could use a bit of math to compute the distance from the element's top edge to the bottom of the screen/page. Using jQuery (for clarity, so the code isn't mucked up with cross-browser feature detection):

var $doc = $(document),
    docHeight = $doc.height(),
    $elt = $('#some-element-id'),
    top = $elt.offset().top,

    // this is the value you're interested in
    originShiftedTop = docHeight - top;

Demo. Try re-running the fiddle with different Result pane heights.


Note that jQuery's .offset() returns the position of the element relative to the document, unlike element.offsetTop the DOM-standard property. jQuery's .position() function behaves like element.offsetTop.

Upvotes: 1

Related Questions