0

I wanted to write a code which should find whether an element exists on screen or not. As per my requirement it should also support for an element which is inside a div that has inner scrolling.

Assumptions are

1.that only one level of inner scrolling should be supported.

2.only visibility in context of vertical scrolling is checked.

The main problem is the following usecase as depicted on this link. An element A ($("#innerele")) is present inside the DIV ($("#outerdiv")) which is scrollable. First you have to find out whether the DIV itself is present on screen and second then test that whether A is visible. For e.g A may be at a the top position inside DIV and thus visible, but if DIV itself is not visible then it should return false.

I could write the following code which is jquery plugin which takes care of the above requirements. The context is the DIV which has inner scrolling inside it.

$.fn.isonscreen = function(context){
    //Subtract the offset of the parent container.
    //Will be 0 in case cont is undefined
    var tominus=0,
    //Add the scrollTop position incase no cont is undefined.
    toadd=0;
    if(context){
        //Find if the div is itself visible
        if(!context.isonscreen()){
            return false;
        };
        tominus = context.offset().top;
    }else{
        context = $(window);
        toadd = context.scrollTop();
    }

    if($(this).offset().top - tominus <= (toadd + context.height())){
        return true;
    };
    return false;
}

For the above link the code to find if A is on screen or not -

$("#innerele").isonscreen($("#outerdiv"))

Will this work everytime or there is some usecase where it will fail?.

agaase
  • 1,362
  • 13
  • 21
  • This question has already been answered [here](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433). – randak Dec 08 '13 at 08:47
  • The solution on the above link doesnt work when I have inner scrolling enabled. E.g it doesnt work here -http://agaase.github.io/webpages/demo/isonscreen2.html. Iam trying to do - isElementInViewport(document.getElementById("innerele")) returns true even innerele is like 200px down the bottom of outerdiv. – agaase Dec 08 '13 at 09:06

0 Answers0