Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Check if an element is visible in viewport

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 3.41k
    Comment on it

    Hi Friends,
    Many times we get into a situation where we want to know whether an element exists within a viewport of browser or not.
    Here below. I am writing a function to check whether an elements exists in a viewport or not.
    It will return true or false and by using this, one can use it in different situations.
    .

    First we will store the DOM element into a variable

    var element = document.getElementById("element_id");
    Case 1:   If we want to know element is completely inside the viewport.
    function checkIfElementIsWithinViewport(element) {
        if((element != undefined) && (element != null)) {
            var element_offets = el.getBoundingClientRect();
            return (
                (element_offets.top >= 0) &&
                (element_offets.left >= 0) &&
                (element_offets.bottom <= window.innerHeight) && 
                (element_offets.right <= window.innerWidth)
            );    
        } else {
            return false;
        }
    }
    

    Case 2:  If we want to any part of the element is inside the viewport.

    function checkIfElementIsPartiallyInViewport(element) {
        if((element != undefined) && (el != null)) { 
              var ele_top = element.offsetTop;
              var ele_left = element.offsetLeft;
              var ele_right = element.offsetWidth;
              var ele_bottom = element.offsetHeight;
    
              while(el.offsetParent) {
                el = element.offsetParent;
                ele_top += element.offsetTop;
                ele_left += element.offsetLeft;
              }
    
              return (
                ele_top < (window.pageYOffset + window.innerHeight) &&
                ele_left < (window.pageXOffset + window.innerWidth) &&
                (ele_top + ele_bottom) > window.pageYOffset &&
                (ele_left + ele_right) > window.pageXOffset
              );
    
        } else {
            return false;
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: