views:

359

answers:

1

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 with another window? The overall goal is to swap out an advertisement only when the current ad is not visible to the user.

One idea would be to have a very simple, invisible Java Applet communicate with the page every time the paint() method is called. I'm pretty sure this would work but I'd like to avoid using applets if possible.

+5  A: 

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() {
    function isScrolledIntoView(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() {
    function isScrolledIntoView(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);
Paolo Bergantino
Cool, thanks. I tried searching both this site and google in general but I was having a hard time summing up exactly what I wanted to do. If you have a link to the original question I can close this one.
Outlaw Programmer