Changing the color of text with Javascript - javascript

I'm trying to make a program where I use a function to change the color of pre-written text using an array and a for loop, depending on what the user inputs when prompted. Here is my code:
// <Student Name> <Student ID> comment must be here.
// This function will change the color of the text to the name of the color you give it.
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
for (var i = 1; i <= 4; i++) {
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
changeColor(colors[colNumber]);
} else {
changeColor("black");
}
}
<html>
<head>
<title>Lab 7 Task 2</title>
</head>
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
</html>
What happens is the text will only show once I've done all of the prompts. It shows the proper color and text and everything, but at the start the "The color is black." doesn't show up, and nothing does until the last prompt is answered.
Note that this is for a beginner class so anything much more advanced than what I have here won't be of much help. I did not write the function, it is there as part of the assignment. I've been at this for hours and can't figure out the issue!

Use SetInterval for this.
check the following code snippet
function changeColor(colorText) {
var text = document.getElementById("colorpar");
text.innerHTML = "<font color=\"" + colorText + "\">The color is " + colorText + ".</font>";
}
// Declare, create, and put values into your color array here
var colors = new Array(5);
colors[0] = "green";
colors[1] = "blue";
colors[2] = "yellow";
colors[3] = "orange";
colors[4] = "red";
// Create a loop that runs 4 times.
// Each time it asks the user for a number between 0 and 4.
// If an invalid input is entered, the color displayed should be black.
// Otherwise display the color at that index in the array.
var x = 0;
var intervalId = setInterval(function() {
if (x == 4) {
clearInterval(intervalId);
}
var colNumber = window.prompt("Enter a number from 0 to 4:");
if (colNumber == 0 || colNumber == 1 || colNumber == 2 || colNumber == 3 || colNumber == 4) {
setTimeout(changeColor(colors[colNumber]), 1000);
} else {
changeColor("black");
}
x++;
}, 100);
<body bgcolor="white">
<h1 id="colorpar">
The color is black.
</h1>
<h1>
</h1>
</body>
Hope this helps

Related

This code is breaking really bad if i remove the bold line

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="message-el">Want to play?</h1>
<p id="cards-el"></p>
<p id="sum-el"></p>
<button onclick="startGame()">Start Game</button>
<button onclick="newCard()">New Card</button>
<script src="abc.js" defer></script>
</body>
</html>
let firstCard = 10
let secondCard = 4
let cards = [firstCard,secondCard]
let sum = firstCard + secondCard
let isAlive = true;
let blackJack = false;
let msg = ''
let showMsg = document.getElementById('message-el')
let showCards = document.getElementById('cards-el')
let showSum = document.getElementById('sum-el')
function startGame(){
renderGame()
}
function renderGame(){
showCards.textContent = 'Cards: ' it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why
for (let i = 0; i<cards.length; i++){
showCards.textContent += cards[i] + " "
}
showSum.innerText = "Sum:" + sum;
if(sum <= 20){
msg = 'Draw a new card?'
}else if(sum === 21){
msg = 'BlackJack!'
blackJack= true
}else{
msg='Lose'
isAlive = false
}
showMsg.innerText = msg;
}
function newCard(){
let card = 1;
sum += card
cards.push(card)
console.log(cards)
renderGame()
}
sorry for this quantity of code,but i really want to make it clear and understand the logic
it looks that if i remove this line my code will print on screen 10 4 10 4 1 when i press new card instead of just 10 4 1 and i don't understand why
The initialisation of showCards.textContent = 'Cards: ' is important, as it removes the previously displayed cards.
This is needed because the loop that follows will iterate over all dealt cards and add them to the showCards.textContent output -- all of them. So if that textContent already had some cards from the previous turn, they will be duplicated.

The sum cannot show although i click on the button

What I want is, after the user enters the number of subjects, the system will show the number of input box according to the number of subjects entered, then when the user clicks on the button, it should show the sum. I tried many ways, but I failed to show the sum, anyone knows what is the mistake I made?
Below is my code:
function select() {
var x = parseInt(document.getElementById('1').value);
if (document.getElementById('1').value == "") {
alert("Please fill up number of subject");
} else if (isNaN(x) == true) {
alert("Please fill up number of subject with number");
} else {
var subject = parseInt(document.getElementById('1').value);
var sum = 0;
for (var num = 1; num <= subject; num++) {
document.write("Enter the mark for subject " + num + " : ");
var value = parseFloat(document.write("<input/><br>"));
sum += value;
}
var calc = document.write("<button>Next</button><br>");
calc.onclick = function() {
next()
};
function next() {
document.write("Total marks: " + sum + "%");
}
}
}
<html>
<body>
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</body>
</html>
That's how I have rewritten a big part of your code. I have place inline comments to explain what I do.
function select() {
var x = parseInt(document.getElementById('1').value, 10);
// Getting the div that wraps the initial form.
var formWrapper = document.querySelector('.formWrapper');
// Getting the div, that is going to display the new fields and the results.
var results = document.querySelector('.results');
// I have switch your statement from x == '' to '' === x as it
// consists a good practice
if ( '' === x ) {
alert("Please fill up number of subject");
// I have remove the isNaN(x) == true, because the isNan will
// be either true or false.
} else if ( isNaN(x) ) {
alert("Please fill up number of subject with number");
} else {
// Using parseInt(x, 10) to set the base.
var subject = parseInt(x, 10);
// In this array, I store the auto-generated fields.
var fieldsList = [];
// Removing the first div from the DOM
formWrapper.parentElement.removeChild(formWrapper);
for ( var num = 1; num <= subject; num++ ) {
// I am creating a new field
var newField = document.createElement('input');
// I push the field into the array I made for the fields.
fieldsList.push(newField);
// I append the field in the HTML
results.appendChild(newField);
// I create a <br> tag
var br = document.createElement('br');
// And I append the tag in the DOM
results.appendChild(br);
}
// I create the button that is going to handle the Next functionality
var nextButton = document.createElement('button');
// I set the button text
nextButton.innerText = 'Next';
// I add an Event Listener for the click event.
nextButton.addEventListener(
'click',
function() {
// I reset the sum to 0
var sum = 0;
// I itterate the fields auto-generated and saved in the array
fieldsList.forEach(
function(field) {
// I get the value
sum += parseInt(field.value, 10);
}
);
// I create the field that is going to display the output
let resultText = document.createElement('div');
// I set the text based on the sum
resultText.innerText = "Total marks: " + sum + "%";
// I append the text message to the DOM
results.appendChild(resultText);
}
);
// I append the button to the DOM
results.appendChild(nextButton);
}
}
<html>
<body>
<div class="formWrapper">
Enter the number of subject: <input type="text" onkeypress="return/[0-9]/i.test(event.key)" id="1" value=""><br>
<button onclick="select()">Check</button><br>
</div>
<div class="results"></div>
</body>
</html>

How to reset variables to original, vanilla Javascript?

I'm making a simple hangman game in vanilla javascript and would like the game to reset after a player losses. Specifically, I'd like to:
1. reset the "guessRemain" variable
2. clear out the "guess" id, so none of the guessed letters are shown
3. choose another random word from the array.
Thanks in advance for your help!
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Hangman Game</title>
<link rel="stylesheet" type="text/css" href="assets\css\reset.css"/>
<link rel="stylesheet" type="text/css" href="assets\css\style.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<script src="https://use.fontawesome.com/ca6de464ee.js"></script>
</head>
<body>
<div id="white">
<img src="assets\images\turkey.png" alt="turkey" class="turkeyImage">
</div>
<div id="orangebox">
<h4>thanksgiving</h4>
<h4 class="hangman">hangman</h4>
</div>
<div class="instructions">
<h1>Instructions:</h1>
<br/>
<h2>1. Guess a Thanksgiving dish!</h2>
<br/>
<h3>2. Press any key to begin.</h3>
</div>
<div class="display">
<p class="greywords">Current Word:</p>
<br/>
<p id="current"></p>
<br/>
<br/>
<p class ="greywords">Number of Guesses Remaining:</p>
<br/>
<p id="remain"></p>
<br>
<br/>
<p class="greywords">Letters Already Guessed:</p>
<p id="guess"></p>
<br>
<br/>
<p class="greywords">Wins:</p>
<p id="win"></p>
<br>
<br/>
<p class="greywords">Losses:</p>
<p id="loss"></p>
</div>
<!-- End of HTML -->
<script type="text/javascript">
// Step 2: create variable of the food words
var wins = 1;
var losses = 1;
var guessRemain = 10;
var foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Step 1: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
var randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
var count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
var remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
//Step 7: function for when they click a key
document.onkeyup=function(event) {
var userGuess = event.key;
document.getElementById("guess").innerHTML += userGuess + " ";
// console.log(randomWord.length);
if (randomWord.includes(userGuess)) {
// console.log("test");
// Step 7: if this statment is true, then modify the count variable, replace the dash in count with letter, and it has the correct position, and display the letter
var guessIndex = randomWord.indexOf(userGuess);
//console.log(randomWord.indexOf(userGuess));
count[guessIndex] = userGuess
//console.log(count);
document.getElementById("current").innerHTML = count;
remainingLetters--;
console.log("I HAVE " + remainingLetters + " left");
if (remainingLetters === 0) {
document.getElementById("win").innerHTML = wins++;
console.log("I have won");}
}
// Step 8: if not true, then subtract a guess
else {
document.getElementById("remain").innerHTML = guessRemain--;
document.getElementById("remain").innerHTML = guessRemain;
if (guessRemain === 0) {
document.getElementById("loss").innerHTML = losses++;
console.log("I have lost");
}
}
}
// Step 10: if there are no letters remaining in count, then add "1" to the win id and reset the page
// if (remainingLetters === 0) {
// document.getElementById("#win").innerHTML = winSs++;
// console.log("I have won");
//console.log("i win");
// function reset() {
// document.getElementById("display").reset();
// }
// }
// Step 11: if there are no guesses remaining, add a "1" to the loss id and reset the page
// if (remainingGuess < 0) {
// document.getElementById("#loss").innerHTML = ++1;
// function reset() {
// document.getElementById("display").reset();
// }
// }
</script>
</body>
<div class="footer">
</div>
</html>
Simply set the variable, so to "reset" guessRemain you'd just type
guessRemain = 10;
inside your reset function, The same would go for any other variables.
As for the Guesses already displayed on the web page, you'd do something similar to this
document.getElementById("guess").innerHTML = "";
Hope that helps :)
First off, clear the guess element somewhere in steps 1-6 by setting its innerHTML to an empty string. Take your steps 1-6 and put them in a function called initialize like so:
Edit: declare your variables wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters outside of the function below so that you'll have access to them in your onkeyup handler
var wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters;
function initialize() {
// Step 1: create variable of the food words
wins = 1;
losses = 1;
guessRemain = 10;
foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Clear the guess
document.getElementById("guess").innerHTML = "";
// Step 2: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
}
Call the function initialize() somewhere in your code (outside of the onkeyup handler) to initialize your game for the first time.
Now, you can reuse the initialize function whenever you want to reset your game. For example, you can do something like this when the game is over (place this code inside your onkeyup handler towards the bottom):
if (remainingLetters === 0 || remainingGuess === 0) {
inititalize();
}

JavaScript function runs for 1 second then clears?

So I've written a web page with a few JavaScript functions.
The page runs perfectly in Dreamweaver but when I tried it out in a browser (Google Chrome and Firefox) the JavaScript flashes for a split second then clears. I have no idea at all why this is.
<body>
<form name="myForm">
<ol>
<li>
<h1> TILE CALCULATOR</h1>
</li>
<li>
<label for="wall height">Wall height (cm)</label>
<input type="text" id="wall_height" />
</li>
<li>
<label for="wall width">Wall Width (cm)</label>
<input type="text" id="wall_width" />
</li>
<li>
<label for="tile height">Tile Height (cm)</label>
<input type="text" id="tile_height" />
</li>
<li>
<label for="tile width">Tile Width (cm)</label>
<input type="text" id="tile_width" />
</li>
<button onclick="javascript:validate();"> Calculate </button>
</ol>
</form>
<br />
<p id="result"></p>
<br />
<canvas id="myCanvas">
Your browser does not support this feature</canvas>
<br />
<br />
<script language="javascript" type="text/javascript">
//functoin to validate the inputs by the user
//user can only enter a number and all fields must be filled
function validate()
{
//first make sure canvas is clear
clearCanvas()
//take the inputs as variables
var x = document.getElementById("tile_width").value;
var y = document.getElementById("tile_height").value;
var z = document.getElementById("wall_width").value;
var i = document.getElementById("wall_height").value;
//check if the user has entered nothing and alert if they have
if (x==null || x=="" || y==null || y=="" || z==null || z=="" || i==null || i=="")
{
alert("All the fields have to be filled out!");
clearResult();
}
// check if the user has entered invalid values, only numbers can be entered
if (isNaN(x) == true || isNaN(y) == true || isNaN(z) == true || isNaN(i) == true)
{
alert("Dimensions can only be numbers!");
clearResult();
}
//check for negatives
if (x <= 0 || y <= 0 || z <= 0 || i <= 0)
{
alert("invalid dimension input, positive non-zero values only");
clearResult();
}
//if valid calculate tiles and print
else
tileCalculator();
}
function tileCalculator()
{
//take the input as variables
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//find the areas of the tile and the wall
var tileArea = tileWidth * tileHeight;
var wallArea = wallWidth * wallHeight;
//divide these to find the number of tiles needed
var noOfTiles = (wallArea/tileArea);
//prints the result of noOfTiles
document.getElementById("result").innerHTML=" The number of Tiles you will need are : " + noOfTiles;
//scalled tiles to the canvas width of your choice
var scalledWidth = 500;
var ratioHW = wallHeight/wallWidth;
var scalledHeight = ratioHW*scalledWidth;
//scaled tile sizes
//scale the tiles to correct pixels
var scalledTileWidth = (tileWidth/wallWidth)*scalledWidth;
var scalledTileHeight = (tileHeight/wallHeight)*300;
//finds the number of tiles needs in a row
var noWidth = wallWidth/tileWidth;
//number of tiles in a column
var noHeight = wallHeight/tileHeight;
var canvas = document.getElementById("myCanvas");
canvas.style.width=scalledWidth + "px";
canvas.style.height=scalledHeight + "px";
printWall(0,0,noWidth,scalledTileWidth,(scalledTileHeight/2),noHeight);
}
//print a tile given the position and dimensions
function printTile(x,y,tileWidth,tileHeight)
{
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillRect(x,y,tileWidth,tileHeight);
}
//prints one row of tiles given the starting position and number to be printed
function printTileRow(x,y,numberOfTiles,tileWidth,tileHeight)
{
var start = 0;
//loops upto number of tiles in a row
while (start < numberOfTiles)
{
//prints a tile each time
printTile(x,y,tileWidth,tileHeight);
//next brick position
x = x + (tileWidth + 1); // add a space between tiles here.
start++;
}
}
//prints the wall
function printWall(x,y,numberOfTiles,tileWidth,tileHeight,numberOfRows)
{
//holds whether last row was shifted
var shiftCount = 0;
//starting index
var start = 0;
//loop up adding a row until required number of rows
while (start < numberOfRows)
{
//prints half a tile at the start of each row
printTile(0,y,(0.5 * tileWidth - 1),(tileHeight));
//prints the row
printTileRow((x+shiftCount),y,numberOfTiles,tileWidth,tileHeight);
//if shifted
if (shiftCount > 0)
{
//was shifted last row
shiftCount = 0;
}
else
{
//was not shifted last row
shiftCount = shiftCount + (0.5*tileWidth);
}
start++;
//start next row
y = y + (tileHeight + 1);
}
}
//clears the canvus each time the button is pressed
function clearCanvas()
{
//reset canvus to 300 by 300 and clear
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
canvas.style.height="300px";
canvas.style.width="300px";
context.clearRect(0,0,300,300);
}
function clearResult()
{
document.getElementById("result").innerHTML="";
}
</script>
</body>
I would really appreciate it if someone could have a quick look for me! Thanks,
Try using onclick="javascript:validate();" on the form tag instead of on the button tag and try using 'onsubmit' instead of 'onclick'
Just replace your onclick attribute by onclick='validate(); return false'.
OR (better then previous)
Just add a type="button" attribute to your button tag, once the HTML5 button's default behavior is to submit forms.
Useful tip
Bind your handler programatically, this way (with no jQuery):
<button type="button" id="calculate"> Calculate </button>
...
window.addEventListener("load", function(){
document.getElementById("calculate").addEventListener("click", validate);
});
there is no problem with kepping the button in the form you you need to return false everytime to avoid the form submit using the return false like this
onclick="javascript:validate();return false;"

button checking a checkbox using javascript

I am trying to make a button that will toggle between three colors: black, green, and red and will either check a certain box depending on the color. Right now I can make the color toggle but I can't make the check boxes check. I would appreciate the help. I am a beginner (obviously).
Button color green: check box 1
Button color red: check box 2
Button color black: do not check either box 1 or 2
The script looks like:
<script>
var colors = ["green", "red", "black"]
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
}
</script>
The HTML looks like:
<html>
<button onclick="setColor(this)">This is my Button</button>
<input type="checkbox" name="box1" id="box1" />
<input type="checkbox" name="box2" id="box2" />
</html>
Thanks!
I'd suggest:
var colors = ["green", "red", "black"];
function setColor(el) {
el.colorIdx = el.colorIdx || 0;
el.style.color = colors[el.colorIdx++ % colors.length];
document.getElementById('box1').checked = el.style.color == 'green';
document.getElementById('box2').checked = el.style.color == 'red';
}
JS Fiddle demo.
Do it like this:
var index = el.colorIdx++ % colors.length;
if( index == 2 ) //2 is the index of color black
{
document.getElementById("box1").checked = false;
document.getElementById("box2").checked = false;
}
else if( index == 0 )
{
document.getElementById("box1").checked = true;
}
else
{
document.getElementById("box2").checked = true;
}

Categories

Resources