Search code examples
javascriptcssbackground-imagebackground-color

Add fade-in/fade-out to background change


i'm pretty new to javascript but I finally could get this working. I can change the backgroundColor. But it's switching hard and I was wondering, if I can add a fade-in/fade-out if I change the backgroundColor from one to the other button.

var btn1 = document.getElementById("tab1");
var btn2 = document.getElementById("tab2");

btn1.addEventListener('click', function (event) {
    changeColor('blue');
});
btn2.addEventListener('click', function (event) {
    changeColor('green');
});

function changeColor(color){
  var elem = document.getElementById( "area" );
  elem.style.backgroundColor =color;

I was also thinking about to change the colors to images.


Solution

  • You can set a transition to the element by CSS like this:

    button {
        -webkit-transition: background-color 1000ms linear;
        -ms-transition: background-color 1000ms linear;
        transition: background-color 1000ms linear;
    }
    

    I recommend checking out this documentation