How to use fadein() to change background color?

Asked

Viewed 1,147 times

1

I would like the tanposition between the colors to have a fade effect. Who knows using .fadein().

$(function () {
    var colors = ["#0099cc", "#c0c0c0", "#587b2e", "#990000", "#000000", "#1C8200", "#987baa", "#981890", "#AA8971", "#1987FC", "#99081E"];
    setInterval(function(){
        var bodybgarrayno = Math.floor(Math.random() * colors.length);
        var selectedcolor = colors[bodybgarrayno];
        $("body").css("background", selectedcolor);
    }, 3000);
})
  • If you use fadeIn()/fadeOut() in your body all the content of your page will disappear along with it. If the goal is to change only the background color these two functions are not the most recommended.

2 answers

2

I suggest using CSS to do this, it’s quite simple, just need to :

body{
    transition: background-color 1s;
}

And to change the speed just needs to change 1s which means 1 second.

$(function () {
    var colors = ["#0099cc", "#c0c0c0", "#587b2e", "#990000", "#000000", "#1C8200", "#987baa", "#981890", "#AA8971", "#1987FC", "#99081E"];
    setInterval(function () {
        var bodybgarrayno = Math.floor(Math.random() * colors.length);
        var selectedcolor = colors[bodybgarrayno];
        $("body").css("background", selectedcolor);
    }, 3000);
})
body{
    transition: background-color 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

Try using the animate, I know div works but I don’t know in body.

$("body").animate({
          backgroundColor: selectedcolor
}, 1000);

I couldn’t test because I’m on my cell phone, but I think it’s gonna happen.

  • Make the color change I can, as code above, the problem is to include a fade effect between changes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.