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.
CodePudding user response:
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
CodePudding user response:
You can use transition
to animate a style change, then use classList.add
and classList.remove
to add/remove the classes that contain the new color.
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.classList.remove('blue', 'green')
elem.classList.add(color);
}
#area {
padding: 50px;
margin-bottom: 15px;
transition: background-color 1s;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
<div id='area'></div>
<button id='tab1'>button 1 </button>
<button id='tab2'>button 2 </button>