Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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