user3810167
user3810167

Reputation:

Compare ScrollTop With offset.top of element

I have this code to calcule top of element and compare with the scrollTop and do any action.

The problem is , it not enter to the condicional "if"

Any idea ?

jQuery( document ).ready(function() {

   var h = parseInt(jQuery(".noticiasFoldsHome").height()) / 2 ;

   var x = parseInt(jQuery(".noticiasFoldsHome").offset().top) - parseInt(h);

   jQuery(window).scroll(function (event) {
        var scroll = jQuery(window).scrollTop();
        //console.log(scroll);

        if ( parseInt(scroll) == parseInt(x) ){
            console.log("entro");
        }

    });



});

Upvotes: 2

Views: 3750

Answers (1)

Sachin
Sachin

Reputation: 1218

You need to add height, not subtract it.

var x = parseInt(jQuery(".noticiasFoldsHome").offset().top) + parseInt(h);

I guess you are trying to do something when user enters some element, if so you might want to use a range in if condition like greater than top of element and less that bottom of element.

scroll event is not called for every pixel, it is called when the scrolling is interrupted. it can go like this 0, 79, 156, 210, 350 and so on. basically randomly. so by trying to compare it with single value, you are actually trying your luck. you better use some range for it. element should be between top of element and top of element + total height of element

Moreover you have used a class name for your jquery selector which indicates there can be more than one element with that class, but this code can work for only first such element. So be cautious.

Upvotes: 1

Related Questions