How to update a JavaScript generated HTML variable - javascript

I created this little background color changer just for fun and to play around with JS for a bit but I'm having a problem I don't really know how to solve.
This is my HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
</div>
</body>
</html>
and my JS:
const button = document.querySelector("#main_button");
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
function changeBackground(){
document.body.style.backgroundColor = randomColor();
};
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);
And this is my problem, every time I click on the button a new paragraph is being generated with the new color code. But I want the button to update the color code in the same paragraph.

on every click you are adding another p tag - instead create a p tag in your html page-
<p id="colorTag"><p>
in your createParagraph function -
instead of let par = document.createElement("p"); do let par = document.getElementById('colorTag') par.innerHTML = "Current color is " + color;

You are actually creating a new <p>-element every time you call createParagraph().
Instead, you can create a tag in your HTML beforehand, and save its reference (which you can get by querying for it using e.g. document.querySelector()) in a variable.
Then, you can change its content by assigning a new value to its .textContent-property.
Here a demonstration:
var pElement = document.querySelector('#p-id');
document.querySelector('button').addEventListener('click', () => {
pElement.textContent = "This is its new text, assigned using the '.textContent'-property!";
});
<button>Change <p>'s content!</button>
<p id="p-id">This is the initial text.</p>
An important note would be, that you are actually not displaying the current color-value. You are calling randomColor() twice: Once in changeBackground(), and once in createParagraph(), while the created color is only used for either assigning <body> a new background-color or being displayed using the <p>-tag.
To display the actually used color, you need to use the same String for both the assignment and the value of <p>'s content. You can do that by one of the following:
Write both use-cases in one function
Use another variable for the color
Use the value of document.body.style.background (or .backgroundColor, depending on what you used). However, this will return the color in a format like rgb(123, 213, 132), which might be unwanted.
I'll show examples for points 1 and 2.
Point 1 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeAndUpdateColor() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
}
button.addEventListener('click', changeAndUpdateColor);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Point 2 could look like this:
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
var color = '';
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.background = color;
}
function updateParagraph() {
pElement.textContent = 'Current Color is ' + color;
}
function getNewColor() {
color = randomColor();
}
button.addEventListener('click', getNewColor);
button.addEventListener('click', changeBackground);
button.addEventListener('click', updateParagraph);
<button id="main_button">Change Color</button>
<p id="p_id"></p>
However, using this many functions and listeners makes the code look clunky. Instead, you should make use of ES6's function expressions or arrow function expressions.
When using a function expression, we can initialize and use the color-variable inside, making a global variable useless.
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
<button id="main_button">Change Color</button>
<p id="p_id"></p>
Speaking of global context:
Declaring many variables and/or functions in the global context will pollute the global namespace, and will be accessible to the user e.g. using the browser-console. This is a problem for functions where sensitive data is handled or accessible.
To free up the global namespace, we can place most of our script inside a so called IIFE, an immediately invoked function expression. Adding this would be as simple as placing your code inside one like this:
(function() {
// Your code ...
})();
The brackets around the function expression itself will group it so it can be executed using the calling brackets (), much like placing a number inside brackets will allow us to call a function on it, like this:
(123).toString();
One further note now would be, that function declarations inside blocks (means: when not declared in the global context) are not part of ECMAScript, making this a non-standardized feature. This might be irrelevant to you, since it is supported in most (if not all) modern browsers anyway. However, in these cases, one should use function expressions referenced by a variable, e.g. like this:
(function() {
var aFunction = function() {
// ...
};
aFunction(); // Executed as usual
})();
Note that function expressions are not hoisted, unlike function declarations, meaning they need to come before their usage in the code.
Accessing characters of a String like accessing entries of an array is another non-standardized feature, again supported in most browsers. The standardized way would be to use String.charAt().
Refactoring your code could look like this:
// Is OK to be globally accessible
function randomColor(){
let letters = "0123456789ABCDEF";
let color = "#";
for(let i = 0; i < 6; i++){
color += letters.charAt(Math.floor(Math.random() * 16));
}
return color;
}
// Should be placed inside an IIFE; the global context is still accessible
(function() {
const button = document.querySelector('#main_button');
const pElement = document.querySelector('#p_id');
button.addEventListener('click', function() {
let color = randomColor();
document.body.style.background = color;
pElement.textContent = 'Current Color is ' + color;
});
})();
<button id="main_button">Change Color</button>
<p id="p_id"></p>

If I understand you correctly, then you want to change the backgroundcolor to the newest paragraph color. Therefor you have to call the changebackground function in the createParagraph function:
function createParagraph(){
let color = randomColor();
const div = document.querySelector(".container");
let par = document.createElement("p");
par.innerHTML = "Current color is " + color;
div.appendChild(par);
changeBackground(color);
}
function changeBackground(newcolor){
document.body.style.backgroundColor = newcolor;
};
button.addEventListener("click", createParagraph);
This would do the job.

You every time create a new paragraph -
HTML File :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-
beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-
giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous"
/>
<title>Color picker</title>
</head>
<body>
<div class="container d-flex align-items-center justify-content-center">
<div>
<button id="main_button" class="btn btn-danger">Change color</button>
</div>
<p id="par"></p> <!-- <== You Need this for render every time color -->
</div>
<script src="./script.js"></script>
</body>
</html>
JS File:
const button = document.querySelector("#main_button");
function randomColor() {
let letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function changeBackground() {
document.body.style.backgroundColor = randomColor();
}
function createParagraph() {
let color = randomColor();
const div = document.querySelector(".container");
let par = document.getElementById("par"); // select paragraph as html file
par.innerHTML = "Current color is " + color; // and render color to paragraph
}
button.addEventListener("click", changeBackground);
button.addEventListener("click", createParagraph);

Related

Random color each 5 seconds [duplicate]

This question already has answers here:
js get by tag name not working
(3 answers)
Closed 9 months ago.
I have the code for the random color that i took it from someone from here but i does not work when I try to put it in the h3 tag can anyone help me?
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function(){
h3.style.color = generateRandomColor()
}, 5000);
Your issue here is that your h3 variable refers to an HTMLCollection, not a single Element. For this reason, you need to loop over those elements, rather than trying to set the style directly on h3, like so:
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function(){
Array.from(h3).forEach(function (elem) {
elem.style.color = generateRandomColor();
})
}, 5000);
<h3>Test</h3>
<h3>Test2</h3>
<h3>Test3</h3>
If you want them to all be the same color, you would just move the generateRandomColor() outside the loop, like this:
window.setInterval(function(){
var color = generateRandomColor();
Array.from(h3).forEach(function (elem) {
elem.style.color = color;
})
}, 5000);
The problem is that you are trying to get all h3 on the page which returns a list of them. If you only want to change this for a single element then just change getElementsByTagName to querySelector like this.
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.querySelector("h3");
window.setInterval(function(){
h3.style.color = generateRandomColor()
}, 5000);
<h3>Header!</h3>
If you want this to works for all h3 elements you could do it like this instead.
function generateRandomColor()
{
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
if(randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var headers = document.querySelectorAll("h3");
window.setInterval(function(){
for(var h3 of headers) {
h3.style.color = generateRandomColor()
}
}, 5000);
<h3>Header 1!</h3>
<h3>Header 2!</h3>
<h3>Header 3!</h3>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h3 {
font-size : 45px;
}
</style>
</head>
<body>
<h3>Hi Good to see that </h3>
<script>
function generateRandomColor() {
var randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
if (randomColor.length != 7) {
randomColor = generateRandomColor();
}
return randomColor;
// The random color will be freshly served
}
var h3 = document.getElementsByTagName("h3");
window.setInterval(function () {
<!-- setting the random color -->
h3[0].style.color = generateRandomColor();
}, 5000);
</script>
</body>
</html>

How to change background color of a div using javascript?

For my course I am making a memory card game. All I want to do here is to change the background color of a div (that has been created in Javascript) when clicked. When the div is clicked, the background color should change to its class name. I included my entire code for your reference, but the part I'm having issues with is the function handleCardClick(event). What am I doing wrong with
(event.target.style.background-color = selectedColor)?
I'm sure it is a simple fix, but any help is appreciated. Love this community!
const gameContainer = document.getElementById("game");
const COLORS = [
"red",
"blue",
"green",
"orange",
"purple",
"red",
"blue",
"green",
"orange",
"purple"
];
// here is a helper function to shuffle an array
// it returns the same array with values shuffled
// it is based on an algorithm called Fisher Yates if you want ot research more
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
let shuffledColors = shuffle(COLORS);
// this function loops over the array of colors
// it creates a new div and gives it a class with the value of the color
// it also adds an event listener for a click for each card
function createDivsForColors(colorArray) {
for (let color of colorArray) {
// create a new div
const newDiv = document.createElement("div");
// give it a class attribute for the value we are looping over
newDiv.classList.add(color);
// call a function handleCardClick when a div is clicked on
newDiv.addEventListener("click", handleCardClick);
// append the div to the element with an id of game
gameContainer.append(newDiv);
}
}
// TODO: Implement this function!
function handleCardClick(event) {
// you can use event.target to see which element was clicked
let selectedColor = event.target.className;
event.target.style.background-color = selectedColor;
}
// when the DOM loads
createDivsForColors(shuffledColors);
#game div {
border: 1px solid black;
width: 15%;
height: 200px;
margin: 10px;
display: inline-block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Memory Game!</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Memory Game!</h1>
<div id="game">
</div>
<script src="script.js"></script>
</body>
</html>
Just check your console log and address the line it says it had an issue with.
There is no such thing as style.background-color, it is style.backgroundColor
Change;
event.target.style.background-color = selectedColor;
to be;
event.target.style.backgroundColor = selectedColor;
Working Snippet:
const gameContainer = document.getElementById("game");
const COLORS = [
"red",
"blue",
"green",
"orange",
"purple",
"red",
"blue",
"green",
"orange",
"purple"
];
// here is a helper function to shuffle an array
// it returns the same array with values shuffled
// it is based on an algorithm called Fisher Yates if you want ot research more
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
let shuffledColors = shuffle(COLORS);
// this function loops over the array of colors
// it creates a new div and gives it a class with the value of the color
// it also adds an event listener for a click for each card
function createDivsForColors(colorArray) {
for (let color of colorArray) {
// create a new div
const newDiv = document.createElement("div");
// give it a class attribute for the value we are looping over
newDiv.classList.add(color);
// call a function handleCardClick when a div is clicked on
newDiv.addEventListener("click", handleCardClick);
// append the div to the element with an id of game
gameContainer.append(newDiv);
}
}
// TODO: Implement this function!
function handleCardClick(event) {
// you can use event.target to see which element was clicked
let selectedColor = event.target.className;
event.target.style.backgroundColor = selectedColor;
}
// when the DOM loads
createDivsForColors(shuffledColors);
#game div {
border: 1px solid black;
width: 15%;
height: 200px;
margin: 10px;
display: inline-block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Memory Game!</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Memory Game!</h1>
<div id="game">
</div>
<script src="script.js"></script>
</body>
</html>
event.target.style.backgroundColor = selectedColor;
function myFunction() {
var test = document.getElementById('test');
test.style.backgroundColor = "green"
}
<!DOCTYPE html>
<html>
<head>
<style>
.test
{
width: 100px;height:300px;background:red;}
</style>
</head>
<body>
<div class="test" id="test">testt</div>
<button type="button" onclick="myFunction()">Set background color</button>
</body>
</html>
Try this

How can I use JavaScript to grab a random div?

I'm using JavaScript to create a grid. What I'm trying to do is have a random box that is created change colors when I click on the "Play" button but I cannot seem to get it figured out.
I've tried using various amounts of Math.random(), this might be where my problem is.
const container = document.getElementById('container');
const gameButton = document.createElement('button');
// This is the button I'm trying to use for this.
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
});
let userInput = prompt('Enter a number between 10-20: ');
if (isNaN(userInput)) {
alert('Numbers only.');
location.reload();
} else if (userInput < 10) {
alert('That\'s less than 10');
location.reload();
} else if (userInput > 20) {
alert('That\'s greater than 20');
location.reload();
} else {
gameButton.textContent = 'Play';
gameButton.style.height = '25px';
gameButton.style.width = '50px';
gameButton.style.borderRadius = '7px';
gameButton.style.marginBottom = '15px';
container.appendChild(gameButton);
}
for (let index = 1; index <= userInput; index++) {
let gameBoard = document.createElement('div');
gameBoard.setAttribute('class', 'game-board');
container.appendChild(gameBoard);
for (let j = 0; j < userInput; j++) {
const square = document.createElement('div');
square.setAttribute('class', 'square');
gameBoard.appendChild(square);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<div id="container">
</div>
<!---<script src="./app.js"></script>--->
</body>
</html>
Expected result is one of the 'divs' changes color when the button is clicked on.
Between your question and your code, it's a little confusing. But just going off what you said, here's a way to choose a random element from a list of elements, provided you give it a class name (feel free to tweak this):
// Function to get a random number, taking in min and max values.
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)
// Function that takes in a class name to select all those elements
// on the page, and returns a random one from the list.
const getRandomElement = className => {
const elements = document.querySelectorAll(`.${className}`)
const num = randomNum(0, elements.length - 1)
return elements[num]
}
You could change the code in your event listener like this:
gameButton.addEventListener('click', function (event) {
let divs = document.getElementsByClassName('game-board');
let random_div = divs[Math.floor(Math.random()*divs.length)];
random_div.style.backgroundColor = 'red';
});
Or if you want only one square to change color, use document.getElementsByClassName('square') instead.
Relevante part o the code. You can make it better checking the elements, the styles, etc. But essentially it is:
gameButton.addEventListener('click', function (event) {
let getRandom = document.getElementsByTagName('div');
var a = Math.random()
let b = a.toString().substr(2, 1)
getRandom[b].style = 'background-color: ' + (parseInt(b) % 2 == 0 ? 'yellow' : 'red')
});
So you use Math.Random to get some random number after the dot(.) and use it to read some index from the collection you get for the getRandom.
Then you just set element style or whatever you want.
The fiddle: https://jsfiddle.net/cm5kyrdj/

Why aren't mouse events working

This is a big piece of code, but if you will indulge me:
<html>
<head>
<style>
.mobile {position: absolute;}
</style>
<script>
var images = new Array();
image['Key1']='image1.png';
image['Key2']='image2.png';
image['Key3']='image3.png';
image['Key4']='image4.png';
image['Key5']='image5.png';
function createAll()
{
tag = document.getElementById("canvas");
for(var key in image)
{
var r = key;
while(r.indexOf('_')>-1)
{
r=r.replace('_',' ');
}
let t = document.createElement("p");
t.id=r;
t.className="mobile"
t.xVel = Math.floor(Math.random()*50-25);
t.yVel = Math.floor(Math.random()*50-25);
t.xPos = Math.floor(Math.random()*1000)-60;
t.style.left= t.xPos;
t.onclick="clickTag('"+r+"')";
t.yPos=Math.floor(Math.random()*600)-42;
////THIS IS WHERE THE EVENT IS ADDED////
t.addEventListener("onmousedown", function(){clickTag(t);});
////THIS IS WHERE THE EVENT IS ADDED////
t.style.top=t.yPos;
var i = document.createElement("img");
i.src=image[key];
var s = document.createElement("span");
tag.appendChild(t);
t.appendChild(i);
t.appendChild(s);
setTimeout(function() {step(t);},200);
}
}
function restartMe(tag)
{
var x = Math.floor(Math.random()*1000);
var y = Math.floor(Math.random()*600);
var xVel = Math.floor(Math.random()*50-25);
var yVel = Math.floor(Math.random()*50-25);
var r = Math.random();
if(r<.25)//left wall
{
x=-59;
xVel = Math.floor(Math.random()*10);
}
else if(r<.5)//right wall
{
x=1059;
xVel = -Math.floor(Math.random()*10);
}
else if(r<.75)//top wall
{
y=-41;
yVel = Math.floor(Math.random()*10);
}
else//bottom wall
{
y=641;
yVel = -Math.floor(Math.random()*10);
}
tag.xPos = x;
tag.style.left=x;
tag.yPos = y;
tag.style.top=y;
tag.style.xVel=xVel;
tag.style.yVel=yVel;
let t = tag;
setTimeout(function() {step(t);},200);
}
function step(tag)
{
var x = tag.xPos;
var y = tag.yPos;
var dx = tag.xVel;
var dy = tag.yVel;
x+=dx;
y+=dy;
let t = tag;
if(x<-60 || x>1060 || y<-42 || y>642)
{
x=-500;
y=-500;
tag.xPos=x;
tag.yPos=y;
tag.style.left=x;
tag.style.top=y;
setTimeout(function() {restartMe(t);},1000);
return;
}
tag.xPos=x;
tag.yPos=y;
tag.style.left=x;
tag.style.top=y;
setTimeout(function() {step(t);},200);
}
function startGame()
{
var tag = document.getElementById("game");
target = Object.keys(image)[Math.floor(Math.random()*Object.keys(image).length)];
var r = target;
while(r.indexOf('_')>-1)
{
r=r.replace('_',' ');
}
target=r;
tag.innerHTML="Look for the "+target;
}
function clickTag(id)
{
////HERE IS WHERE THE MOUSE EVENT SHOULD EXECUTE////
if(id===target)
{
startGame();
}
var tag = document.getElementById("output");
tag.innerHTML="No, that is the "+id;
}
</script>
</head>
<body onload="createAll();startGame()">
<h2>What do you see?</h2>
<p id="game"></p>
<p id="output"></p>
<p id="canvas" class="black" width="1000" height="600"></p>
</body>
</html>
Okay, here' the run down. I start with several image file names in an array with a key that identifies the image. When the page loads I go through the process of creating set of moveable p tags containing the image and a click event. There is a timeout for each of these tags and then they move across the screen. When one of them reaches a boundary it waits for a second and then starts again from one of the margins. This part works fine, but the mouse event doesn't.
I keep looking for a mouse event when I click on one of those things, but nothing is happening. I have tried putting the event on the p and the img. I have tried variations of onmousedown, onmouseup, onclick, etc. and nothing seems to work. I'm probably missing something obvious, so I'd appreciate a second set of eyes.
First addEventListener does not use "on" in the string
t.addEventListener("mousedown", ...
Now you add all the other events correctly and you call closures with your timeouts, but you build the click event wrong.
t.onclick="clickTag('"+r+"')";
That is assigning a string to the event listener, it is not binding a funciton call.
t.onclick= function () { clickTag(r); };
There's only one instance of createAll in your example, but its shown as a function declaration, so you are never actually executing createAll(), so it's not enabling your event listeners.
Try changing createOne() to createAll().
<body onload="createOne();startGame()">

Alert and prompt not working even after function is called

I'm creating a game that generates a random color which the user must guess. This is the first part but when I try to check the page only the onload message displays. I turned off the pop up blocker. I called the function but still nothing.
<!doctype html>
<html>
<head>
<title>Guess the Color Assignment 2 Part 1</title>
</head>
<body onload="do_game()">
<script type="javascript/text">
var target_index;
var guess_input_text= "none";
var guess_input;
var finished = false;
var guess = 1;
var colors=["blue","yellow","red","green","brown","black"];
colors= colors.sort();
function do_game () {
var random_number = (Math.random() * (colors.length-0)) + 0;
var random_number_integer = Math.floor(random_number);
target_index= random_number_integer;
var target = String(colors[random_number_integer]);
alert("" + target);
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors: \n\n" +
colors.join(",") + "\n\n What color am I thinking of?");
guess_input = colors.indexOf(guess_input_text);
guess += 1;
finished = check_guess();
}
}
</script>
</body>
</html>
Your game works but you need to call a do_game() function to start it. Also check_guess() function is not defined

Categories