I've been working with JS for about two weeks, and I'm working on a little project. The goal was to be able to change the color on each individual character in a given string when pressing the button. I've gotten that far.
As you can see, I added spans to each character, so that I can individually edit them. I'm trying to apply a transition to the spans so that when I click the button, the color fades to another color instead of just instantaneously changing. Is that possible?
Here's the codepen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="CSS/textColorV2.css">
</head>
<body>
<p id="letter">Color</p>
<button>Click ME</button>
<script type="text/javascript" src="JS/textColorV2.js"></script>
</body>
</html>
CSS
bodybody {
background-color: #FFE7E0;
}
span{
transition: all 4s;
}
#letter {
font-size: 9em;
position: absolute;
top: 30%;
left: 50%;
transform: translate(-50%, -50%);
color:blue;
}
JS
var letter = document.getElementById("letter");
var text = letter.innerHTML;
var button = document.querySelector("button");
button.addEventListener("click", function () {
var newText = "";
for (var i = 0; i < text.length; i++) {
newText += '<span style="color:' + randomColor() + '">' +
text.charAt(i) + '</span>';
letter.innerHTML = newText;
letter.classList.add("trans");
};
});
function randomColor() {
//r
var r = Math.floor(Math.random() * 256);
//g
var g = Math.floor(Math.random() * 256);
//b
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + " ," + g + " ," + b + ")";
}