0

How does one locate the nearest HTML fragment identifier (hashtag href) based on window's current scroll position?

I want to make a bookmarking feature via JS/jQuery that captures the nearest section the user was in when hitting the bookmark button. I don't have access to the backend, so I can't add any hooks/hidden fields, but that shouldn't matter because the fragment IDs are my hooks.

I'm thinking jQuery's .scroll() handler could be of use, but I'm not sure how to locate the "DOM content at a given scroll position" to know if a new identifier has appeared. Or if that's even the best approach...

Thoughts?

dooleyo
  • 851
  • 1
  • 9
  • 13

3 Answers3

2

Something like that:

$('a [href]').filter(function() {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(this).offset().top;
    var elemBottom = elemTop + $(this).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
})
.first();
Artur Udod
  • 3,968
  • 23
  • 53
  • based on : http://stackoverflow.com/questions/487073/check-if-element-is-visible-after-scrolling – Artur Udod Aug 06 '13 at 21:33
  • Thanks Artur. While I found a better approach for my situation (I added it as another answer), this is technically a correct answer to my original question. – dooleyo Aug 06 '13 at 22:01
1

While not technically an answer to my original question, this is the more flexible solution I decided to use:

When the user hits "bookmark" jQuery will store the page url with a phantom query string tacked on of pos=X where X is the current value of $('body').scrollTop().

When a user wants to revisit his bookmark, the stored URL will be loaded and the inserted jQuery will retrieve the pos value and scroll the page to the bookmarked position.

This is ideal because it literally puts the user right back where he/she left off, down to the pixel.

dooleyo
  • 851
  • 1
  • 9
  • 13
0

i quite don't understand your question, but to do something on scroll using jquery you can try this.

$(document).ready(function(){
    $(window).scroll(function(){
        if ($(window).scrollTop() > 100){
            /*you check if identifier has appeared here*/
        }
    });
});
Ronny Kibet
  • 3,025
  • 4
  • 27
  • 42