Search code examples
javascriptjqueryscrollfrontendparallax

jQuery scrollTop won't be made negative


I am using this code I found online:

var background_image_parallax =
function($object, multiplier) {
    multiplier = typeof multiplier !== 'undefined' ? multiplier : 0.5;
    multiplier = 1 - multiplier;
    var $doc = $(document);
    $object.css({"background-attachment" : "fixed"});
    $(window).scroll(function() {
        var from_top = $doc.scrollTop(),
        bg_css = '0px ' +(multiplier * from_top) + 'px'
        $object.css({"background-position" : bg_css
        });
    });
};

The problem is: I would like to manipulate the 2nd (y component) of bg_css. When I change the "+" symbol in front of (multiplier * from_top) to "-", the code breaks. I also wanted to try subtracting 400px from bg_css's y component, but whenever I manipulate this code in the slightest, it breaks.


Solution

  • Here you're using + as the concatenation operator. To make it negative try this:

        var from_top = $doc.scrollTop(),
        bg_css = '0px ' +(multiplier * from_top * -1) + 'px'
    

    Alternately:

    bg_css = '0px ' +(-multiplier * from_top) + 'px'