erol_smsr
erol_smsr

Reputation: 1496

Check to see which element is visible in viewport (not if a specific element is visible)

I have a scrollable div and when I scroll I need to detect the currently visible item inside the div. I've found many solutions that allow to see if a specific element is in the viewport. I need a function that simply shows which item is visible, without having to specify the specific element. The function does have to check if the visible item has a specific class and it should show which one of the elements with that class name is visible.

I have this right now:

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

However, this returns true or false according to the visibility of a specific element. I need a functions that grabs the currently visible element (and returns that element).

How can I achieve that?

Edit @starky's answer is exactly what I need, but I also need to be able to get the data from the element's data attribute. Adding the data() method returns an error saying data() isn't a function (which I don't understand as this method returns an HTML element.) How can I access the attributes of the returned element?

Upvotes: 1

Views: 291

Answers (1)

starky
starky

Reputation: 640

Using jQuery:

$('*').filter(function() {
    return isScrolledIntoView(this);
});

You can change the wildcard * selector to match any set of elements. For example, if you only want to get visible buttons, you can write:

$('button').filter(function() {
    return isScrolledIntoView(this);
});

Upvotes: 1

Related Questions