Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Luca Botticelli
PLUS
Luca Botticelli
Courses Plus Student 8,753 Points

Parallax to background-position

Hello, I'm trying to create a parallax with a background-image inside a <div> with jQuery. This is the code:

CSS

<style>
#upper-space, #under-space {
    width: 100%;
    height: 914px;
}
#image {
    width: 100%;
    background-image: url(../img/myimage.jpg);
    height: 100px;
    background-size: 1773px;
    background-position-x: 666px;
    background-position-y: 250px;
}
</style>

JavaScript

<script>
/* position 250 is the position of the window when I want the image to start moving */
var position = 250;
$(window).scroll(function(){
    var scroll = $(window).scrollTop();
    /* if the position is less than 250 I want the image to stop moving (this works) */
    if (scroll <= 250) {
        $('#image').css("background-position-y", + "250px");
        position = 250;
    }
    /* I also want that the image to stops moving if the position is more than 930 (and this     works too) */
    else if (scroll >= 930) {
        $('#image').css("background-position-y", + "935px");
    }
    else if (scroll > position) {
        $('#image').css("background-position-y", + position + "px");
        position += 2;
    } 
    else if (scroll < position) {
        $('#image').css("background-position-y", + position + "px");
        position -= 2;
    } 
});
</script>

HTML

<body>
    <div id="upper-space"></div>
    <div id="image"></div>
    <div id="under-space></div>
</body>

The problem is that when I scroll down to the bottom, then scroll to the top and then scroll to the bottom again, I see the image position jumping or sometimes even going up when it should go down.

Could you please help me to fix this issue ? Thank you in advance