Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ID of the div at current position

Tags:

jquery

I have n number of <section> in a page. Each one is provided with id such as 'page1', 'page2'...

At the top I place 2 buttons say Previous and Next. When Previous is pressed it will be scrolled to the Previous <section>. Similarly to the next <section> on pressing Next Button.

But now the problem is when a user scrolls the page using the scroll bar, how can I detect which <section> the user is viewing?

like image 681
Sarvap Praharanayuthan Avatar asked Mar 19 '13 09:03

Sarvap Praharanayuthan


1 Answers

You can check if your section is in the "ViewPort", i am using this to find out:

function isTotallyInViewPort($entry){
    var windowScrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var windowVisibleBottom = windowScrollTop + windowHeight;
    var entryTop = $entry.offset().top;
    var entryOuterHeight = $entry.outerHeight();
    var entryVisibleBottom = entryTop + entryOuterHeight;

    var isInView = windowScrollTop < ( entryTop ) < (windowVisibleBottom);
    if(!isInView) return false;

    var isCompleteInView = ( entryVisibleBottom ) < (windowVisibleBottom);
    return isCompleteInView;
}

if you want to detect if PARTS are shown, just create a function that checks if the current view is overlapping with the position of your section.

you may bind it to $(window).on("scroll")

edit: i think this should detect if your elements are shown (not tested yet)

function isPartlyInViewPort($entry){
    var windowScrollTop = $(window).scrollTop();
    var windowHeight = $(window).height();
    var windowVisibleBottom = windowScrollTop + windowHeight;
    var entryTop = $entry.offset().top;
    var entryOuterHeight = $entry.outerHeight();
    var entryVisibleBottom = entryTop + entryOuterHeight;

    var isAboveViewPort = entryVisibleBottom < windowScrollTop;
    var isBelowViewPort = windowVisibleBottom < entryTop;

    return !(isAboveViewPort || isBelowViewPort);
}
like image 179
FibreFoX Avatar answered Oct 23 '22 18:10

FibreFoX