0

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..

Dave
  • 1,076
  • 5
  • 15
  • 30

2 Answers2

3
$(window).scroll( function() {
    if($(this).scrollTop() > height_of_image) {
        $('body').css('background-attachment','fixed');
    } else {
        $('body').css('background-attachment','none');
    }
});

Plagiarised from here

Community
  • 1
  • 1
Patrick Beardmore
  • 1,026
  • 1
  • 11
  • 35
  • 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 09: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
0

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.

Luke Carbis
  • 345
  • 2
  • 12