2

I have been trying to figure this out and I keep riddling myself to nowhere.

I have a blog with all the posts numbered chronologically from 1 to X (class), each page of the blog displays 10 posts, each with a numbered anchor (post1, post2, etc).

I can't figure out how to retrieve the id/class/name of the anchor of the element currently displayed on the screen (where the scrollbar is) if the user didn't get to the anchor by clicking a link.

Can this even be done? I'm trying to code it in JavaScript but I don't know where to start, a nod in the right direction would help a lot.

  • Please try this [parsing url method][1]. [1]: http://stackoverflow.com/questions/3552944/how-to-get-the-anchor-from-the-url-using-jquery – AChudov Nov 28 '12 at 03:40

2 Answers2

0

If the anchor's id/name isn't in the URL then you could try combining a function to get absolute position of elements

function pos(e) {
    var o = {left:e.offsetLeft, top:e.offsetTop};
    while (e=e.offsetParent)
        o.left = o.left + e.offsetLeft,
        o.top = o.top + e.offsetTop;
    return o;
}

with a loop over document.getElementsByTagName('a') (or some other list of nodes you want to check)

and check window.scrollY <= o.top && o.top <= window.scrollY + window.innerHeight to find if the <a> is in the window.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

I would test all anchor links for being visible in the viewport. You'll need to decide which one to pick if more than one is visible.

How to tell if a DOM element is visible in the current viewport?

Community
  • 1
  • 1
goat
  • 31,486
  • 7
  • 73
  • 96