Everyone talks about transitioning things in CSS, but have you ever thought about transitioning background colors in JavaScript? I'm currently working on a function that changes the background color of a div with the id of ex1 to green. However, I'm facing an issue where the setInterval function is only running once, which is quite strange.
CSS:
<style type="text/css">
div#ex1{color:white; background:black; width:300px; padding:0px 10px 10px; margin-bottom:10px;}
div#ex1:hover{cursor:pointer;}
div#ex1 h2{border-bottom:double 3px white; text-align:center; padding: 5px 0; margin: auto -10px;}
div#ex1 p{text-indent:5px;}
</style>
HTML
<div id="ex1">
<h2>Transition Color</h2>
<h4>Text:</h4>
<p>Church-key seitan listicle locavore, mixtape biodiesel readymade crucifix health goth flexitarian direct trade mlkshk iPhone. Banjo tote bag readymade +1 skateboard deep v. Mixtape cred readymade gentrify. Banh mi keytar butcher, skateboard knausgaard </p>
</div>
Javascript:
document.getElementById('ex1').addEventListener('mouseover', function(e){
var tar = this;
var counter;
var backG = window.getComputedStyle(tar,null).getPropertyValue('background-color');
console.log(backG);
var re,gr,bl;
gr = 0;
bl = 0;
function chColor(tar)
{ gr =+31;
bl=+10;
if ( gr <153 && bl <51)
{ console.log('This is running');
tar.style.backgroundColor = 'rgb(0,'+gr+','+bl+')';
}
else
{
clearInterval(counter);
console.log(backG);
console.log('The change has ended');
}
}
counter = setInterval(chColor(tar),100);
}, false);