Skip to content Skip to sidebar Skip to footer

Is There A Way To Detect When An Html Element Is Hidden From View?

Using Javascript, is it possible to detect when a certain element is no longer visible, such as when the user scrolls down far enough or when the browser is minimized or covered wi

Solution 1:

I am not sure if there is a way to detect if a window is over the element or if the window is minimized (although I think you may be able to do the latter by hooking something into the window's blur? I'm not sure...). Anyhow, as far as scrolling, that part of the question has been asked a few times before, and this is the quick demo I came up with to show how to do it. In the example something happens when the element is scrolled into view, but the logic is of course the same. Anyhow, the code is:

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

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

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

    var myelement = $('#formcontainer');
    var mymessage = $('#mymessage');
    $(window).scroll(function() {
        if(isScrolledIntoView(myelement)) {
            mymessage.hide();
        } else {
            mymessage.show();
        }
    });
});

There's not much jQuery-specific about it so you can take that stuff out:

window.addEventListener('load', function() {
    functionisScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

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

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

    var el = document.getElementById('myelement');
    window.addEventListener('scroll', function() {
        if(isScrolledIntoView(el)) {
            // do something when element is scrolled into view
        } else {
            // do something when it is not in view
        }
    }, false);
}, false);

Post a Comment for "Is There A Way To Detect When An Html Element Is Hidden From View?"