How to display rainbow message in console.log - javascript

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>

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. :)

Related

JS select correct line in select list

I am using this JS code to do some magic. Working perfect to get a variabele and remove unwanted text and display the correct text in a text field.
values 2 or 3 or 5 or 7 etc. in <input type="text" id="calc_dikte[0][]" name="calc_dikte[]" value="">
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
if(isNaN(elems_1_split_2[0])) { elems_2[i].value = ''; }
else { elems_2[i].value = parseFloat(elems_1_split_2[0]); }
}
}
}
So this works, but now the form field has changed from text to select like:
<select id="calc_dikte[0][]" name="calc_dikte[]">
<option value="">
<option value="2|2000">2</option>
<option value="3|2000">3</option>
<option value="5|2000">5</option>
<option value="7|2000">7</option>
</select>
Therefore I have changed my JS code (with some tips from here) to:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var sel = elems_2[i];
var val = parseFloat(elems_1_split_2[0]);
for(var m=0, n=sel.options.length; m<n; m++)
{
if(sel.options[i].innerHTML === val)
{
sel.selectedIndex = m;
break;
}
}
}
}
}
But this is not working, no item is selected in the select list, no errors are shown.
Please help me out change to a working code to have the correct line selected. It should not select on the value but in the text between the ><
option value="5|2000">5</option
If I check with
for(var m=0, n=sel.options.length; m<n; m++) {
alert('sel = '+sel.options[i].innerHTML+'\nval = '+val);
}
I see that val is correct. But sel is just the number as used in $i so 0 1 2
You are using a strict equals operator to compare a Number (parseFloat) agains .innerHTML, which is always a string.
Convert sel.options[i].innerHTML to a Number aswell:
if (parseFloat(sel.options[i].innerHTML) === val) {
sel.selectedIndex = m;
break;
}
If you want to filter out invalid numbers (NaNs), use !isNaN(val) aswell.
Code to get this working:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var val = parseFloat(elems_1_split_2[0]);
var sel = elems_2[i];
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++)
{
if (opt.text == val)
{
sel.selectedIndex = j;
break;
}
}
}
}
}

Trouble with showing time in Javascript

I created an easy game with Javascript, the purpose is to pick a square who has a RGB color(random generated) from a list of squares and show the length of time until the square with the correct color is found. Everything works fine, except after the time is shown corectly and I click on a button, the time continues to change and show again a new time and i don't want that. I try to give display: none or textcontent ="" after showing the time, but is not working.
The problem is in these lines:
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
Thanks!
The game link: https://ionutbedeoan.github.io/joc/
My javascript code :
var numSquares = 6;
var colors = generateRandomColors(numSquares);
var squares = document.querySelectorAll(".square");
var pickedColor = pickColor();
var colorDisplay = document.getElementById("colorDisplay");
var messageDisplay = document.querySelector("#message");
var h1 = document.querySelector("h1");
var resetButton = document.querySelector("#reset");
var easyBtn = document.querySelector("#easyBtn");
var hardBtn = document.querySelector("#hardBtn");
var numSquares = 6;
var timp = document.getElementById("timeTaken");
var start = new Date().getTime();
var end;
var timeTaken;
easyBtn.addEventListener("click", function () {
start = new Date().getTime();
numSquares = 3;
this.classList.add("selected");
hardBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < 3; i++) {
squares[i].style.backgroundColor = colors[i];
}
for (var i = 3; i < squares.length; i++) {
squares[i].style.display = "none";
}
timp.textContent= "";
messageDisplay.textContent = "";
h1.style.background = "steelblue";
});
hardBtn.addEventListener("click", function () {
start = new Date().getTime();
this.classList.add("selected");
numSquares = 6;
easyBtn.classList.remove("selected");
colors = generateRandomColors(numSquares);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = colors[i];
squares[i].style.display = "block";
}
messageDisplay.textContent = "";
timp.textContent= "";
h1.style.background = "steelblue";
});
resetButton.addEventListener("click", function () {
start = new Date().getTime();
//generare noi culori
colors = generateRandomColors(numSquares);
//alegem o noua culoare random din vector
pickedColor = pickColor();
//schimbam colorDisplay sa fie la fel cu culoarea aleasa
colorDisplay.textContent = pickedColor;
//schimbare culori ale patratelor
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
}
h1.style.background = "steelblue";
messageDisplay.textContent = "";
this.textContent = "Culori noi";
timp.textContent= "";
});
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++) {
// adaug culorile la fiecare patrat
squares[i].style.background = colors[i];
//cand dau click pe un patrat
squares[i].addEventListener("click", function () {
// pun intr-o variabila culoarea patratatului ca sa o verific cu culoarea pe care trebuie sa o ghicesc, pentru a vedea daca am nimerit culoarea
var clickedColor = this.style.backgroundColor;
if (clickedColor === pickedColor) {
messageDisplay.textContent = "Corect!"
resetButton.textContent = "Joc nou"
changeColors(clickedColor);
h1.style.backgroundColor = clickedColor;
end = new Date().getTime();
timeTaken = (end - start) / 1000;
timp.style.display ="inline";
timp.innerHTML = "Timpul tau: " + timeTaken + " s.";
} else {
this.style.backgroundColor = "#232323";
messageDisplay.textContent = "Gresit!";
}
});
};
function changeColors(color) {
//schimbam culoarea la fiecare patrat
for (var i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = color;
}
}
function pickColor() {
var random = Math.floor(Math.random() * colors.length);
return colors[random];
}
function generateRandomColors(num) {
// fac un vector
var arr = [];
//adaugam numarul de culori random
for (var i = 0; i < num; i++) {
//alegem o culoare random si o bagam in vector
arr[i] = randomColor();
}
//returnam vectorul
return arr;
}
function randomColor() {
// alegem un rosu intre 0 si 255
var r = Math.floor(Math.random() * 256);
//alegem un verde intre 0 si 255
var g = Math.floor(Math.random() * 256);
//alegem un albastru intre 0 si 255
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
Thanks !
Check if the correct answer was already selected in your square's event listener and return if so. This will prevent it from running the rest of the event listener's code where it updates the time.
if (clickedColor === pickedColor) {
if (messageDisplay.textContent === "Corect!") return;
...
} else {
...
}

random color for every tag

I have this piece of javascript and I need every element "title" to be colored with different randomized color. I accomplished colorize only the first one. It is possible? Thanks
var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById('title').style.color = randomColor;
<div id="title"><a>TEXT1</a></div>...<div id="title"><a>TEXT2</a></div>...
Just invoke changeColor(); functions.
$(function(){
changeColor();
});
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerText;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = ""
for(var j = 0; j < innerTextSplit.length; j++) {
var randomColor =getRandomColor();
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
paragraphs[i].innerHTML += innerTextSplit[j];
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
<p>abcdefthuild</p>
As I already commented, you cannot use duplicate IDs, prefer using a class instead and modify your code accordingly.
var getElm = document.getElementsByClassName('title');
for(var i = 0, l = getElm.length; i < l; i++) {
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
getElm[i].style.color = '#' + randomColor;
}
<div class="title"><a>TEXT1</a></div>
<div class="title"><a>TEXT2</a></div>
Some explanation of how the above code works:
I am using getElementsByClassName which will return me an array of elements you want to target, in this case, it's the ones with the class name of title. Then I loop them, generate a new random hex, and assign it to the looped element.
Make sure you don't forget to concatenate your hexcode with #
Use like this .without classname
using document.querySelectorAll().it will select the element.
Then applied each element with color using Array#forEach
And you are missing # in dom for adding color
document.querySelectorAll("div[id='title']").forEach(function(a){
var randomColor = Math.floor(Math.random()*16777215).toString(16);
a.style.color ='#'+randomColor;
})
<div id="title"><a>TEXT1</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>
<div id="title"><a>TEXT2</a></div>...
HTML
<div class="title"><a>TEXT1</a></div>...
<div class="title"><a>TEXT2</a></div>...
JS
var elements = document.getElementsByClassName('title');
var usedColors = {};
var getRandomColor = function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
while(usedColors[randomColor] === 1) {
randomColor = Math.floor(Math.random()*16777215).toString(16);
}
usedColors[randomColor] = 1;
return randomColor;
};
for (var i = 0; i < elements.length; i++ ) {
var randomColor = getRandomColor();
elements[i].style.color = "#"+randomColor;
}
JSFIDDLE
https://jsfiddle.net/1cuwdLye/

How to dynamically create buttons based on random conditions

I have created a button using JavaScript, and I have a list that is supposed to get a random number when I "roll the dice"
I need to list of numbers to say "You rolled a 1" for example. How do I do that? And also I only need it to show the last 10 numbers.
var rollNumber = 0;
var values = [];
function dieRolled() {
rollNumber += 1;
var numRolled = Math.ceil(Math.random() * 6);
values.push(numRolled);
document.getElementById("results").innerHTML = "";
for (var x = values.length-1 ; x>=0; x--) {
var newRoll = document.createElement("li");
newRoll.innerHTML = values [x] +"You rolled a";
document.getElementById("results").appendChild(newRoll);
if (x == 11)break;
}
}
How about this?
var output = document.getElementById("Output");
var values = [];
function roll()
{
values.push(Math.ceil(Math.random() * 6));
// If the history is too big, drop the oldest...
if (values.length > 10)
{
values.shift();
}
// Rewriting the history log
var text = "";
for (var i in values)
{
text += "You rolled a " + values[i] + "\n";
}
output.innerHTML = text;
}
// Rolling multiple times
setInterval(function(){ roll(); }, 1000);
<pre id="Output"></pre>
Try this:
var list = document.getElementById('demo');
var count = 0;
function changeText2() {
count++;
if(count <= 10)
{
var numRolled = Math.ceil(Math.random() * 6);
var entry = document.createElement('li');
entry.appendChild(document.createTextNode("You rolled:"+numRolled));
list.appendChild(entry);
}
}
<input type='button' onclick='changeText2()' value='Submit' />
<p>Dices you rolled</p>
<ol id="demo"></ol>

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

Categories