Nadjib Mami
Nadjib Mami

Reputation: 5830

Change the URL hash value with the reached div id

Consider the following snippet:

<div id="container">
    <div id="1" class="flag"></div> 
    /* some text */

    <div id="2"  class="flag"></div> 
    /* some text */

    <div id="3"  class="flag"></div> 
    /* some text */
</div>

The container is overflow, it has a scroll bar. I need to change the hash value in the URL with the id of the div reached while scrolling. For example, the scroll bar is in the top/bottom of the container. I start scrolling down/up, once I reach a div, I change the hash value of the URL to the id of this reached div.

This way changes the hash value to a very specific value when I reach a very specific div(JQuery):

                var t = $("#someDiv").offset().top;
                $("#container").scroll(function(){
                    if($(this).scrollTop() > t )
                    {   
                        location.hash = "100";
                    }
                });

What to change to make it work as needed? Any snippets, keywords or links will be appreciated.

Upvotes: 0

Views: 1812

Answers (1)

Christian
Christian

Reputation: 19750

Why not just check every div?

$("#container").scroll(function() {
    $('#container > div').each(function() {
        if( $("#container").offset().top > $(this).offset().top ) {
            window.location.hash = this.id;
        }
    });
});

jsFiddle: http://jsfiddle.net/2ZjWP/

Upvotes: 0

Related Questions