Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I'm working on a website at the moment, and I've got a rather interesting idea for a background image on my website. It's a rather large image so depending on screen size, the bottom half may or may not show.

I was wondering if it was at all possible using jQuery to set the attachment of the background image to fixed, ONLY WHEN the user has scrolled down, revealing the bottom of the image.

The background would be positioned in CSS with "top", and would scroll as normal, until there is no more background image to display, then it will set it's attachment to fixed..

My apologies if this isn't a good explanation, but i'm not exactly sure how to describe it.

Thank you HTML/CSS/JavaScript guru's in advance..

share|improve this question
up vote 3 down vote accepted
$(window).scroll( function() {
    if($(this).scrollTop() > height_of_image) {
        $('body').css('background-attachment','fixed');
    } else {
        $('body').css('background-attachment','none');
    }
});

Plagiarised from here

share|improve this answer
    
Thanks Patrick.. Is there any way to make this a little smoother? At the moment, when height_of_image is reached, it sorta jumps, which makes sense, but a smoother transition would be helpful. – Dave Mar 23 '11 at 9:18
    
Sorry, not sure about that. Would require some clever javascript. You could mess with background-position settings but that's a big faff. – Patrick Beardmore Mar 23 '11 at 17:37
1  
Agreed. Thanks for your answer :) – Dave Mar 24 '11 at 9:10

Sorry to reply to such an old post - but I found a solution that works much better than the current answer, because it doesn't update the background position property every time the user scrolls (which was causing a jittering effect in some browsers).

$(window).scroll(function(){

    if ($(this).scrollTop() + $(this).height() > heightOfImage ) {
        if ( ! $('body').hasClass('stopscroll') ) 
            $('body').addClass('stopscroll');
    } else {
        if ( $('body').hasClass('stopscroll') )  
            $('body').removeClass('stopscroll');
    }

});

Then in your css, do this:

body {
    background: transparent url(images/bg.jpg) center top no-repeat;
    background-attachment: none;
}
body.stopscroll {
    background-attachment: fixed;
    background-position: center bottom;
}

It's less work for the browser, and works a lot smoother.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.