Get divs in viewport inside div wrapper

Is there a way to get elements that:

  • Inside div with overflow: scroll
  • In the viewport

Like the following picture, where the active div (5,6,7,8,9) is orange and the rest are green (1-4 and> 10):

enter image description here

I just want the mousewheel event to add an “active” class to the div 5,6,7,8,9 (currently in viewport). View my JSFiddle

$('.wrapper').bind('mousewheel', function (e) {
   //addClass 'active' here
});
+4
source share
1 answer

You could do something like this. I would review it, but only to show the concept.

-, scroll, mousewheel. , , .;) .

, overflow:auto; , , .

, , , , - IE clientHeight. , , .

" Fiddle" "

function isView(wrp, elm)
{
    var wrpH = $(wrp).height(),
        elmH = $(elm).height(),
        elmT = $(elm).offset().top;

    return elmT >= 0 && 
           elmT + elmH < wrpH;
}

$('.wrapper').bind('scroll', function (e) {
    $('div.box').each(function(i, e) {
        if (isView(".wrapper", this)) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
});

, , , , .wrapper , , ..


; isView(). . .

" Fiddle" "

function isView(pool, dolphin) {
    var poolT = pool.offset().top,
        poolH = pool.height(),
        dolpH = dolphin.height(),
        dolpT = dolphin.offset().top - poolT;
    return dolpT >= 0 && dolpT + dolpH <= poolH;
}
+3

Source: https://habr.com/ru/post/1526139/


All Articles