toing_toing
toing_toing

Reputation: 2442

Jquery scroll function to determine whether div is within viewport not working

I am trying to build a function which checks whether a set of divs are within the visible viewport. I have the following code:

$(window).scroll(function(){
    var $w = $(window);
    var bottom_edge_y = $w.scrollTop()  + $w.height();
    var top_edge_y = $w.scrollTop();

    $('#itin_list').children('div').each(function () {
        var scrollTop = $(window).scrollTop(),
        divOffset = $('#'+ $(this).attr('id')).offset().top,
        if(top_edge_y < divOffset< bottom_edge_y){
            alert("caught");
        }
    });
)};

However this code alerts every time, even if the divOffset is not within the range specified in the if condition. What is the issue? Thanks in advance.

Upvotes: 0

Views: 218

Answers (1)

burp_dude
burp_dude

Reputation: 51

There is a problem with your if condition. You cannot compare 3 numbers in a single comparison like this.

Instead of `if(top_edge_y < divOffset< bottom_edge_y), 

use this:

 if(top_edge_y < divOffset &&  divOffset<bottom_edge_y)`

Upvotes: 1

Related Questions