Reputation: 187
Hi have a script for rainbowtizing console.log output.
When i try, console.log output raw string, but if i copy this output in another console.log, he output the message with the correct color.
Do you know why ?
var input = document.getElementById('input');
input.addEventListener("blur", function() {
var inputValue = input.value;
var inputSplitted = inputValue.split("");
let i = 0,
inputLength = inputSplitted.length;
var newLog ='"';
var colors = "";
for(i=0; i<inputLength; i++){
// Chaque lettre est contenue dans inputSplitted[i]
newLog += "%c"+inputSplitted[i];
colors += ',"color: '+randomColor()+';"';
}
newLog +='"';
var log = newLog+colors;
console.log(log);
console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});
function randomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<input type=text name=input id=input>
Upvotes: 3
Views: 1418
Reputation: 1836
As is said in the comment the browser handles the string just as a string and not as parameters.
You have to declare an array and use console.log.apply
.
Have a look:
var input = document.getElementById('input');
input.addEventListener("blur", function() {
var inputValue = input.value;
var inputSplitted = inputValue.split("");
let i = 0,
inputLength = inputSplitted.length;
var newLog ='';
var colors = "";
for(i=0; i<inputLength; i++){
// Chaque lettre est contenue dans inputSplitted[i]
newLog += "%c"+inputSplitted[i];
colors += '||color: '+randomColor()+';';
}
newLog +='';
var log = newLog+colors;
var arr = log.split('||');
console.log.apply(console, arr);
console.log("%ch%ce%cl%cl%co%c %cw%co%cr%cl%cd","color: #144143;","color: #40C71F;","color: #5B7487;","color: #E3E226;","color: #6A8693;","color: #EC8802;","color: #9D44DE;","color: #1F1C4D;","color: #92812D;","color: #7A412C;","color: #73936F;");
});
function randomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<input type=text name=input id=input>
Hope this code will help you. :)
Upvotes: 2