Pregunta

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?

¿Fue útil?

Solución

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();

Otros consejos

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.

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*/
        }
    });
});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top