Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript [solved] simple background scroll

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #174028
    Gary Pickles
    Participant

    Hi all, Im trying to scroll the background image in a div as the page scrolls to create a simple parallax scroll effect.

    this code works, injecting the style onto #wrapper
    <script>
    $(document).ready(function() {
    $(window).scroll(function() {
    var pos = $(window).scrollTop()
    $(‘#wrapper’).css({“background-position”: “50% 200px'”});
    console.log(pos)
    });
    });
    </script>

    but as soon as i try to use the Var pos as the second position, nothing happens.

    <script>
            $(document).ready(function() {
                $(window).scroll(function() {
                    var pos = $(window).scrollTop()
                    $('#wrapper').css({"background-position": "50% +pos+'px'"});
                    console.log(pos)
                });
            });
        </script>
    

    just need to inject one css property to alter the div’s background position.

    Thanks
    Gary

    #174038
    Senff
    Participant

    This specific situation can be done much simpler without jQuery; just add background-attachment:fixed; to the #wrapper.

    But if you have to use jQuery (in case you want to do more with it), your syntax is slightly wrong. Try this instead:

     $('#wrapper').css('background-position','50% '+pos+'px');
    

    See it in action: http://codepen.io/senff/pen/akHcJ

    #174043
    Gary Pickles
    Participant

    Thank you Senff, work like a charm, was just going to add a multiplier to the Var ‘pos’ so the background scrolled at a slightly different speed.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.