Nick
Nick

Reputation: 3281

Javascript/jQuery turn DOM in single object

I currently have:

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

var items = document.getElementsByClassName('item');
The var items contains 'object HTMLCollection'
I want to check if the divs are visible on the screen, I know how to do that, but I need the divs in different Objects in jquery/javascript so I can check if the object is in the screen when the user scrolls (I'm using $( window ).scroll)

How do I achieve this?

Upvotes: 1

Views: 98

Answers (2)

A. Wolff
A. Wolff

Reputation: 74410

You could use custom :inview pseudo-selector, to implement it: https://gist.github.com/Demwunz/2251871

$.extend($.expr[':'], {
    inview: function(el) {
        var e = $(el),
            w = $(window),
            wt = w.scrollTop(),
            wb = wt + w.height(),
            et = e.offset().top,
            eb = et + e.height();

        return eb >= wt && et <= wb;
    }
});

Then inside onscroll handler:

$(window).on('scroll', function(){
    //do something with: 
    $('.item:inview') // .item elements in viewport
    //or with:
    $('.item:not(:inview)') // .item elements out of viewport
});

Upvotes: 0

Buisson
Buisson

Reputation: 539

I think you want this :

$('.item').each(function(){
    var element = $(this);//element contain the element selected for one iterate
    //here your code to check one div is visible
});

Upvotes: 2

Related Questions