0

I have a certain identical div on my webpage one below the other .I want to get the correct position of the div to certain message(which is absolutely positioned and fades out later).

so I tried this

$('.divs_article').click(function() {
    var left=$(this).offset().left;
    var top=$(this).offset().right;
});

but this is giving incorrect results for the div that lie below the page,when I scroll down.

Is there any better approach.?

(PS:I have already tried this.)

Community
  • 1
  • 1
Naveen
  • 7,944
  • 12
  • 78
  • 165
  • 1
    "`the correct position`" related to what? Another element? document.body? viewport? – Teemu Feb 09 '14 at 10:39
  • What Teemu said. Also, as a general rule for jQuery, have the practice to set `var $this = $(this), $offset = $this.offset();`. – MaxArt Feb 09 '14 at 10:41
  • Relative to the screen,where you view the div – Naveen Feb 09 '14 at 10:42
  • 1
    I.e. related to viewport? If so, [`getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect) is probably what you need. – Teemu Feb 09 '14 at 10:45

1 Answers1

0

A little thought worked for me,

Here the simple trick

$("div_article").offset().top-$(document).scrollTop()

(PS:I was a dumb question,hope it helps someone in future)

Naveen
  • 7,944
  • 12
  • 78
  • 165
  • 1
    IIRC, jQuery's `offset` method actually relies on `getBoundingClientRect`, and adds the page's scrolling amounts if no argument is given. – MaxArt Feb 09 '14 at 10:47