Find Scroll Position of a Particular Object

Asked

Viewed 19,079 times

9

It is possible to know the position of the scroll of a given object through pure Jquery or Javascript? tried var posobj = $("#meuobjeto_id").scrollTop(); However, the obtained value is always 0. Any idea? I wanted that when the user passes by a certain object (not clicking, or passing the mouse, but scrolling the page) the object is animated, for this I want to use the scrollTop()

2 answers

11


For steps, what you need to do is:

  1. know the position of the element you want on the page to be able to compare with the scroll value at a given time.

  2. have an event receiver that measures the current amount scroll at every moment of the scroll

  3. compare the current scroll with the object’s initial position and act upon a condition if

A example that I made for another question:

var posicaoInicial = $('#meuobjeto_id').position().top;
$(document).scroll(function () { // oscultador de scroll
    var posicaoScroll = $(document).scrollTop(); // obtem a quantidade de scroll no momento
     if (posicaoInicial < posicaoScroll) $('#meuobjeto_id').animate({'opacity': 1}, 500);
})

The if (posicaoInicial < posicaoScroll) compose the values and run the .animate() when the scroll is larger than the initial position of its element.

3

Utilize offset to find the object’s position

$("#meuobjeto_id").offset().top

And compare the $(window).scrollTop() with the value obtained. You can do something like

$(window).scroll(function(){
    if ($("#meuobjeto_id").offset().top > $(window).scrollTop()){
        // animar
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.