views:

375

answers:

1

I'm trying to create a messagebox that is fixed to the bottom of a webpage, so when a user scrolls, it stays put (simple css). However, I'd like the messagebox to disappear when the user scrolls to a certain point in the webpage.

For example, if you have a signup form on the bottom of your site, I'd like to create a messagebox that reads "scroll down to signup", and when the user scrolled down to the top of the sign up form, the message would disappear, or get covered up by the form. So when they scrolled up, the message would reappear.

This isn't my implementation, but an accurate illustration of the concept.

I haven't any experience developing with javscript, but was hoping there was an existing method for this. I'm willing to learn though, this is something I'd like to use.

Any thoughts? Or concepts to start learning?

Thanks guys! (I think this could be a really clever method of highlighting certain content that perhaps users would miss if they didn't scroll through the entire page.)

+4  A: 

This should do the trick (tested in IE7, Firefox, Chrome, Safari).

It uses jQuery and shows the element as soon as it is visible. This is the code:

$(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));
    }
    // the element to look for
    var myelement = $('#formcontainer');
    // the element to hide when the above is visible
    var mymessage = $('#mymessage');
    $(window).scroll(function() {
        if(isScrolledIntoView(myelement)) {
            mymessage.hide();
        } else {
            mymessage.show();
        }
    });
});

If you want the whole element to be visible before the message is hidden, replace the isScrolledIntoView above with this:

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)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}

Credit for both of these functions go to this question.

Paolo Bergantino