2

I have two bits of code that I want to merge, but not sure on the actual correct markup and how to write it correctly.

function EasyPeasyParallax() {
  scrollPos = $(document).scrollTop();
    $('#header_nav').css({
        'background-color': 'rgba(0, 0, 0, 0.8)'
      //'opacity': 0.5+(Math.min(scrollPos/100,1))
  });
};

$(function(){
  $('body').bind('mousewheel',EasyPeasyParallax);
});

The opacity selector works when I scroll down the page. However, I want to only target the background color of the div. How can I combine the 'background-color' selector with the scrollPos/100 code?

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
user3817083
  • 79
  • 1
  • 7

2 Answers2

3

You can use this code for animationg background-color's opacity property on scroll event.

jsFiddle Demo

function EasyPeasyParallax() {
    var scrollPos = $(document).scrollTop();
    var targetOpacity = 1;
    scrollPos < 1000 ? targetOpacity = '0.'+ (scrollPos*100)/10 : targetOpacity;
    $('span').css({
        'background-color': 'rgba(0, 0, 0, '+ targetOpacity +')'
    });
    console.log(scrollPos,targetOpacity);
};

$(function(){
    $(window).scroll(function() {
        EasyPeasyParallax();
    });
});

-

If you want to animate background-color with jQuery, inspect this answer:

Special color transition effect with pure jQuery animation // no ui or other libary

Community
  • 1
  • 1
Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
  • 1
    And if you seek good performance, only save the current scroll position in the scroll listener and make an additional RequestAnimationFrame loop that does the rendering. – Alp Jul 08 '14 at 16:06
0
        function EasyPeasyParallax() {
            scrollPos = $(document).scrollTop();
            var opacityVal = 0.5+(Math.min(scrollPos/100,1));
            var rgbaCol = 'rgba(0, 0, 0, ' + opacityVal + ')'
            $('#header_nav').css('background-color', rgbaCol);
        };
Angelo
  • 137
  • 1
  • 11