0

So I'm trying to animate a css property based on scrolling the browser window. the code below works so far, but I'd like it to have a transition instead of just abruptly snapping from an opacity of 1 to an opacity of 0.5. any help is appreciated. thanks in advance.

$(document).ready(function(){
$(window).scroll(function(){
    if ($(window).scrollTop() > 50){
        $('.header').css('background','rgba(200, 54, 54, 0.5)');
    }
    else if ($(window).scrollTop() < 50){
        $('.header').css('background','rgba(200, 54, 54, 1)');
    }
});

});

Here is a jsfiddle link to the code so far

4 Answers 4

2

you can do

 $(window).scroll(function(){
    if ($(window).scrollTop() > 50){
        $('.header').css('background','rgb(200, 54, 54)').stop().animate({"opacity":".5"},1000)
    }
    else if ($(window).scrollTop() < 50){
        $('.header').css('background','rgb(200, 54, 54)').stop().animate({"opacity":"1"},1000)
    }
});    

http://jsfiddle.net/XXjZW/2/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. this code and the following example work great, but it brings me to another question. How can i animate the background opacity with affecting the h1 tag inside the header div?
1

You can use the CSS3 property transition:

.header{
    -webkit-transition:background 1s;
    -moz-transition:background 1s;
    -o-transition:background 1s;
    transition:background 1s;
}

Comments

1

give your css transition ->

transition:background 1s;

http://jsfiddle.net/XXjZW/6/

Comments

1

If you want compatibility with browsers which don't suppor CSS3, I would recommend you to make use of jQuery UI library:

  $('.header').animate({
      backgroundColor: "#aa0000"
  }, 1000);

Living example: http://jsfiddle.net/XXjZW/8/

You will need to include it as you include jQuery library:

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.