Amr Magdy
Amr Magdy

Reputation: 43

Detect the nearest divs to the center screen when scrolling jquery

I want to detect which div is nearest to the screen center, while scrolling horizontally. Once detected, I want to do something such as trigger an event.

enter image description here

var screenW = ($(window).width() /2);

$('div.fistSlider').bind('mousemove', function(e){
    var xN = e.pageX + 16;
    $('div#divContainer').scrollLeft(xN);
});

When the div nearest to red line (the center of screen), should do some event.

Upvotes: 2

Views: 2623

Answers (1)

Donnie D'Amato
Donnie D'Amato

Reputation: 3940

The answer here is to check for the offset of each div.

$(document).scroll(function(){
    $('div').each(function(){
        var centerLine = $(window).width()/2;
        var divStart = $(this).offset().left;
        var divEnd = divStart + $(this).width();
        if(divStart < centerLine && divEnd > centerLine){
            //do the thing
        } else {
            //undo the thing
        };
    });
});

Upvotes: 1

Related Questions