1

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?

2
  • 3
    Loop through the collection. Commented Dec 11, 2014 at 11:53
  • 1
    for(var i = 0; i < items.length; i++) {item = items.item(i); //item is a div.item each iteration} Commented Dec 11, 2014 at 11:57

2 Answers 2

2

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
});
Sign up to request clarification or add additional context in comments.

4 Comments

:visible does not select for elements that are presently within the viewport, but visible in the entire document object.
and if you use : if(element.css({"display"})=="none")
@Buisson will this state that the element is in the viewport/screen currently.
sorry I have misunderstanding the term 'visible'
0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.