Scott Quested
Scott Quested

Reputation: 117

Get element position in viewport as percentage

I am trying to get an elements position (in a percentage value) in relation to the viewport.

I have X amount of elements on the page and when one comes in to view, i would like its position to the current viewport as a percentage. So the viewport top to bottom is 0 - 100% and the element coming in will start at 0% and move to 100% when it just goes out of view.

I need to try and get this value.

this is what i have so far.

<div class="animation-float">
    <img class="u-responsive-img animation-float-item" src="assets/img/Layer-82.png">
    <img class="u-responsive-img animation-float-item-shadow" src="assets/img/Layer-82-shadow.png">
</div>

<script>

    var $animation_elements = $('.animation-float'),
        $window = $(window);

    function check_if_in_view() {

    var window_height = $window.height(),
        window_top_position = $window.scrollTop(),
        window_bottom_position = (window_top_position + window_height);


    $.each($animation_elements, function() {

        var $element = $(this),
            $element_item = $element.find('.animation-float-item'),
            $element_item_shadow = $element.find('.animation-float-item-shadow'),
            element_height = $element.outerHeight(),
            element_top_position = $element.offset().top,
            element_bottom_position = (element_top_position + element_height);

        //check to see if this current container is within viewport
        if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) {

            scrollPercent = Math.round(window_top_position/(element_top_position-window_height)*100);

            console.log(scrollPercent);

        } else {


        }
    });
}

$window.on('scroll resize', check_if_in_view);
$window.trigger('scroll');

</script>

The scrollPercent is the calculation I'm having the problem with (I think).

Thanks in advance

Upvotes: 1

Views: 2056

Answers (1)

digglemister
digglemister

Reputation: 1487

I think this is what you're after:

scrollPercent = Math.round((element_top_position-window_top_position)*100/window_height)

This gives the percentage based on the top of the element, so if the bottom of the element is slightly poking out from the top of the viewport, you will get a negative percent.

Or if you want to get 0% when the bottom of element first peaks out of top of viewport and 100% when the top of the element first vanishes from the bottom of the viewport, use this:

scrollPercent = Math.round(100*(element_bottom_position-window_top_position)/(window_height+element_height))

Upvotes: 2

Related Questions