Search code examples
javascriptcssbackground-position

Javascript Scrolling Parallax Positioning


I'm currently doing a javascript parallax page. I've managed to set the background image and 2 other pictures(#content,#content2).

When i scroll all the way down past my content and then to my content2, I want my webpage to end there. However I'm able to scroll down infinitely.

Can anyone please look at my code and tell me what i need to add or change so that my webpage ends and stops scrolling after content2.

Please note that my #image is my main background and the content and content2 are separate images that go over my background but i want my page and scrolling to stop at content2.

Code:

<style type="text/css">
    * {
        margin: 0px;
        padding: 0px;
    }
    #image {
        position: relative;
        z-index: -1
    }
    #content {
        height:690px;
        width: 100%;
        margin-top:-10px;
        background:url(http:/chicago_bulls_wallpaper_backgrounds.jpg);
        position: relative;
        z-index: 1; 
        background-repeat:   no-repeat;
        background-position: center center;
    }

    #content2 {
        top:710px;
        height:570px;
        width: 100%;
        margin-top:-10px;
        background:url(All.jpg);
        position: relative;
        z-index: 1; 
        background-repeat:   no-repeat;
      background-position: center center
         }

      </style>
    <script type="text/javascript">
    var ypos, image;
    function parallex() {
        ypos = window.pageYOffset;
        image = document.getElementById('image');
        image.style.top = ypos * 1 + 'px';
    }
    window.addEventListener('scroll', parallex);
    </script>
     <img id="image" src="black-glass.png" height="710px" width="100%" />
   <div id="content"></div>
    <div id="content2"></div>

Solution

  • It's because your parallax factor is 1, meaning that the background is moving exactly with the screen. Thus, the browser thinks that it always has room and can always afford to scroll down, which is actually a pretty hilarious bug.

    If you were intending true parallax scrolling, set your factor to less than 1, like this:

    image.style.top = ypos * 0.95 + 'px';
    

    If you simply didn't want your background to move at all with the rest of the page, set the body's background to this image (as you already do with the divs), and set the background-attachment property to fixed - no JavaScript required.