The button only works once - javascript

The following code on the website page creates a button that the user receives a random number at any time by clicking the button:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>rand100.html</title>
<style type = "text/css">
fieldset {
width: 600px;
margin-right: auto;
margin-left: auto;
}
label {
float: left;
width: 250px;
text-align: right;
margin-right: 1em;
clear: left;
}
span {
float: left;
}
button {
display: block;
clear: both;
margin: auto;
}
</style>
<script type = "text/javascript">
function roll(){
//create variables for form elements
var spnRaw = document.getElementById("spnRaw");
var spn100 = document.getElementById("spn100");
var spnFinal = document.getElementById("spnFinal");
//get random number
var raw = Math.random();
spnRaw.innerHTML = raw;
//multiply by 100
var times100 = raw * 100;
spn100.innerHTML = times100;
//get the ceiling
var final = Math.ceil(times100);
spnFinal.innerHTML = final;
} // end roll
</script>
</head>
<body>
<h1>Make random numbers 1 - 100</h1>
<form>
<fieldset>
<label>raw</label>
<span id = "spnRaw">0</span>
<label>times 100</label>
<span id = "spn100">0</span>
<label>final</label>
<span id = "spnFinal">0</span>
<button type = "button"
onclick = "roll()">
roll the dice
</button>
</fieldset>
</form>
</body>
</html>
Now I want to make every user receive just one random number, that is, if the user clicks on the button and receives a random number, and again clicking on the button, this time a new random number will not be displayed.
That is, each user, if more than once, clicks the button, only receives a random number, no more.
How can I do this now?
That is to change the code so that even if the user after opening the site and clicking the button and then receiving the random number, clicked the button again, a new random number will not be received.

Please check the below code. just use a boolean e.g doRoll variable and set it to true. When you call roll() for the first time set the boolean variable to false after getting the random number.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>rand100.html</title>
<style type = "text/css">
fieldset {
width: 600px;
margin-right: auto;
margin-left: auto;
}
label {
float: left;
width: 250px;
text-align: right;
margin-right: 1em;
clear: left;
}
span {
float: left;
}
button {
display: block;
clear: both;
margin: auto;
}
</style>
<script type = "text/javascript">
var doRoll = true;
function roll(){
if(doRoll)
{
//create variables for form elements
var spnRaw = document.getElementById("spnRaw");
var spn100 = document.getElementById("spn100");
var spnFinal = document.getElementById("spnFinal");
//get random number
var raw = Math.random();
spnRaw.innerHTML = raw;
//multiply by 100
var times100 = raw * 100;
spn100.innerHTML = times100;
//get the ceiling
var final = Math.ceil(times100);
spnFinal.innerHTML = final;
doRoll = false;
}
} // end roll
</script>
</head>
<body>
<h1>Make random numbers 1 - 100</h1>
<form>
<fieldset>
<label>raw</label>
<span id = "spnRaw">0</span>
<label>times 100</label>
<span id = "spn100">0</span>
<label>final</label>
<span id = "spnFinal">0</span>
<button type = "button"
onclick = "roll()">
roll the dice
</button>
</fieldset>
</form>
</body>
</html>

You can define the value before the function:
var random = Math.random();
function roll() {
...
}
Or set it inside the function only if it is undefined:
var random;
function roll() {
if (typeof random === 'undefined') {
random = Math.random();
}
...
}
Or create some flag:
var rolled = false;
function roll() {
if (rolled) {
return;
}
...
rolled = true;
}
Or remove an event listener from the button:
function roll() {
...
button.onclick = null;
}
The link to the button object you can get from the event object:
function roll(event) {
...
event.target.onclick = null;
}

Related

How can I show different text on click?

I'm building a simple memory game just to show functionality.
User inserts a string, I shuffle it and present the split chars on the screen - as stars. (* * * *)
Whenever a user will click a star, it will show the real value of the number.
For now I have a text box for input, I shuffle the chars but I'm not sure what is the best way to use that array and present the string as stars that onclick will flip back to the real char. Thanks for helping!
const section = document.querySelector("section");
function myFunction() {
var input = document.getElementById("searchTxt").value;
const x = document.querySelector("p");
const yourInp = "Your input is: "
x.textContent = yourInp;
document.getElementById("str").innerHTML = input;
const cards = input.split('');
const randomize = () => {
cards.sort(() => Math.random() - 0.5);
return cards;
};
const cardsGenerator = () => {
const cards = randomize();
console.log(cards);
cards.forEach(item => {
console.log(item);
});
}
cardsGenerator();
}
<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>Memory Game</title>
</head>
<body>
<h1> Memory Game </h1>
<input name="searchTxt" type="search" maxlength="4" id="searchTxt" class="searchField" value="Word" />
<button onclick="myFunction()">Start Game</button>
<p id="yourstr"> </p>
<p id="str"> </p>
<section></section>
</body>
Maybe you want to check this approach out:
const section = document.querySelector("section");
function myFunction() {
var input = document.getElementById("searchTxt").value;
const x = document.querySelector("p");
const yourInp = "Your input is: " + input;
x.textContent = yourInp;
const cards = input.split('');
const randomize = () => {
cards.sort(() => Math.random() - 0.5);
return cards;
};
const cardsGenerator = () => {
container.innerText = ''; // clear container
const cards = randomize();
cards.forEach(item => {
const d = document.createElement("div"); // create div
d.innerText = '*'; // set text to *
d.onclick = () => { d.innerText = item; } // handle onclick to display real value
container.appendChild(d); // append div as child to container
});
}
cardsGenerator();
}
div.cards {
display: flex;
justify-content: center;
align-items: center;
flex-direction: row;
padding: 3px;
background: gray;
border-radius: 2px;
font-size: x-large;
}
div.cards > div {
display: flex;
justify-content: center;
align-items: center;
margin: 10px;
padding: 10px;
background: white;
border-radius: 6px;
}
<h1> Memory Game </h1>
<input name="searchTxt" type="search" maxlength="4" id="searchTxt" class="searchField" value="Word" />
<button onclick="myFunction()">Start Game</button>
<p id="yourstr"> </p>
<div class="cards" id="container">
</div>

Building a Wheel of Fortune game and I'm trying to get the keypress event to detect a letter in the random word array

I'm working on a Wheel of Fortune game where a random word is chosen from an array. I created a function below my game function to detect the key pressed from a list of letters displayed on screen from A-Z. My problem is that I can't get the game to detect the key pressed until the randomWord() function is fired after the playGame() button is pressed. I'm trying to get the letter pressed by the user in the buttonPress() function to match a letter in the wordChoice.length loop and display on the screen where the _ would be and then rule out the letter after it's been used. I tried creating the letterClicked variable and making it global so that my playGame() function can access it but I'm not having any luck matching the letter selected by the user and the letter in the display box above the play button. What am I doing wrong here? I tried console logging throughout the randomWord() function but the keypress is only being detected after you click play and essentially reset the game. Here is my code below. Thanks for your help!
<DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Wheel of Fortune</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="main.css">
</head>
<body>
<body>
<div id="container">
<div id="header">
<p class="welcome">Welcome to Wheel of Fortune!</p>
<!-- The letters will be tied to the number of letters in the random array -->
<p class="letters">There are <span id="numbers">0</span> letters in this word</p>
<!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
<p class="lives">You have <span id="guesses">0</span> guesses left</p>
<span id="words"></span><br>
<button id="play" onclick="playGame()">Play</button>
</div>
<div id="alphabet" onclick="buttonPress(event)">
<button>A</button>
<button>B</button>
<button>C</button>
<button>D</button>
<button>E</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>I</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>M</button>
<br>
<button>N</button>
<button>O</button>
<button>P</button>
<button>Q</button>
<button>R</button>
<button>S</button>
<button>T</button>
<button>U</button>
<button>V</button>
<button>W</button>
<button>X</button>
<button>Y</button>
<button>Z</button>
</div>
<span id="your-guess">You guessed </span>
</div>
<script src="main.js"></script>
</body>
</html>
body {
margin: 0 auto;
width: 1000px;
font-size: 20px;
background: url("http://res.cloudinary.com/angelrodriguez/image/upload/c_crop,h_624/v1534810805/wheeloffortune.jpg");
background-size: cover;
color: white;
}
#header {
margin: 20px;
}
#alphabet {
margin: 20px;
}
button {
border: 2px solid blue;
font-size: 20px;
}
#words {
font-size: 30px;
margin: 10px;
letter-spacing: 20px;
}
#play {
margin: 20px;
}
// 3. Quit the game if the player wants to.
// 5. Keep track of letters the player has guessed.
// 6. Show the player their progress.
// 7. Finish when the player has guessed the word.
// Create global variables
let gameOver = false;
var guessesLeft = 6;
var letterClicked;
var wordArray = ["JAVASCRIPT", "ARRAYS", "FUNCTIONS", "HOISTING", "RECURSION", "EVENTS", "KEYUP", "TERNARY"];
// 1. Pick a random word.
//Start a new game
function playGame() {
newGame.addEventListener("click", function() {
//fire the randomWord function to generate a new word
randomWord();
})
}
// Pass the letter event from buttonPress into the randomWord function
function randomWord(letter) {
var answerList = [];
// console.log(answerList);
// letterGuessed = "";
console.log(letterClicked);
var wordChoice = wordArray[Math.floor(Math.random() * wordArray.length)];tbw
var wordSplit = wordChoice.split('');
// console.log(wordSplit);
for (var i = 0; i < wordSplit.length; i++) {
answerList[i] = "_";
}
// if the letter is in the word
// Update the players progress with the guess
for (var z = 0; z < wordChoice.length; z++) {
if (wordChoice[z] === letterClicked) {
letterClicked = answerList[i];
// answerList[i].innerHTML = letterGuessed;
}
}
//Display underscores on page representing each word in the random word
wordDisplay.innerHTML = answerList;
//Display number of letters in the random word on the page
var remainingLetters = wordChoice.length;
letterCount.innerHTML = "The word is " + remainingLetters +
" letters long";
}
// 2. Take the player’s guess.
function buttonPress(e) {
letterClicked = e.target.textContent;
document.getElementById("your-guess").innerHTML = "You guessed the letter " + letterClicked;
//fix issue with clicking divs
}
// If the player wants to quite the game {
// Quit the game
// }
// Grab elements
var numbers = document.querySelector("#numbers");
var guesses = document.querySelector("#guesses");
var wordDisplay = document.querySelector("#words");
var letterCount = document.querySelector(".letters");
var newGame = document.querySelector("#play");
var letterBoxes = document.querySelector("#alphabet");
To get a letter in buttonPress you are able to use e.toElement.textContent.
I did some solution, but it's not a great example, i think.
let words = [ "TERNARY"], guessesLeft, chosenWord;
let getRandomWord = words => {
return words[Math.floor(Math.random()*words.length)];
}, updateGuesses = count => {
guesses.innerText = count;
guessesLeft = count;
}, updateWords = word => {
document.getElementById('words').innerHTML = word;
}, hideAlphabet = () => alphabet.style.display = 'none',
setGameStatus = status => document.getElementById("status").innerHTML = status;
play.addEventListener('click', e => {
e.target.style.display = 'none'; // hide when game started.
alphabet.style.display = 'block';
chosenWord = getRandomWord(words);
updateGuesses(chosenWord.length);
updateWords(String("*").repeat(chosenWord.length))
});
alphabet.addEventListener('click', e => {
let letter = e.toElement.textContent;
e.toElement.disabled = true;
if (!new RegExp(letter).test(chosenWord)) {
updateGuesses(guessesLeft -1);
} else {
let newString = document.getElementById('words').innerHTML.split(''), indexesOfALetter = [];
for(let i = 0; i < chosenWord.length; i += 1) // here for is a fastest way.
if (chosenWord[i] === letter) indexesOfALetter.push(i);
indexesOfALetter.forEach(i => newString[i] = letter);
updateWords(newString.join(''));
}
if (!/\*/.test(document.getElementById('words').innerHTML)) {
hideAlphabet();
setGameStatus("Congratulations! You won that game");
}
if (guessesLeft < 1) {
hideAlphabet();
setGameStatus("Unfortunately, you lost the game ;(");
updateWords(chosenWord);
}
});
body {
margin: 0 auto;
width: 1000px;
font-size: 20px;
color: black;
}
#header {
margin: 20px;
}
#alphabet {
display: none;
margin: 20px;
}
button {
border: 2px solid blue;
font-size: 20px;
}
#words {
font-size: 30px;
margin: 10px;
letter-spacing: 20px;
}
#play {
margin: 20px;
}
<div id="container">
<div id="header">
<p class="welcome">Welcome to Wheel of Fortune!</p>
<!-- The user will be given a number of choices and with each wrong choice, they lose a turn -->
<p class="lives">You have <span id="guesses">0</span> guesses left</p>
<span id="words"></span><br>
<button id="play">Play</button>
</div>
<div id="alphabet">
<button>A</button>
<button>B</button>
<button>C</button>
<button>D</button>
<button>E</button>
<button>F</button>
<button>G</button>
<button>H</button>
<button>I</button>
<button>J</button>
<button>K</button>
<button>L</button>
<button>M</button>
<br>
<button>N</button>
<button>O</button>
<button>P</button>
<button>Q</button>
<button>R</button>
<button>S</button>
<button>T</button>
<button>U</button>
<button>V</button>
<button>W</button>
<button>X</button>
<button>Y</button>
<button>Z</button>
</div>
<span id="status"></span>
</div>

Putting JavaScript data inside an HTML table cell

I am building a pop up box that every time someone fires it (with delay), a counter displays that shows the number of clicks and the dates of the clicks!
How can I get the time and the clicks to be shown in a cell table something like this:
Clicks Time
1 thusday 4 2018
2 monday 3 2018
Here is my HTML code:
function Msg1() {
document.getElementById('myText').innerHTML = 'Hey <strong>Thanks!</strong>';
}
var counter1 = 1;
var popup = document.getElementById("popup");
var input = document.getElementById("popup-delay");
var showButton = document.getElementById("popup-show");
var closeButton = document.getElementById("popup-close");
showButton.addEventListener("click", function onShowClick() {
// Get the user input and convert it into a number
var value = parseInt(input.value, 10);
// If the input is not a number
if (isNaN(value)) {
// Warn the user
alert("NaN (Not A Number) !");
}
// Otherwise
else {
// Convert milliseconds to seconds
var delay = value * 1000;
// Turn off the click listener on the "Show" button
showButton.removeEventListener("click", onShowClick);
// Start the countdown to show the popup
document.getElementById("num1").innerHTML = counter1;
counter1 = counter1 + 1;
document.getElementById("num4").innerHTML += "<span>" + Date() + "</span>";
setTimeout(function() {
// Show the popup
popup.style.display = "block";
// Turn on the click listener on the "Close" button
closeButton.addEventListener("click", function onCloseClick() {
// Turn off the click listener on the "Close" button
closeButton.removeEventListener("click", onCloseClick);
// Turn on the click listener on the "Show" button
showButton.addEventListener("click", onShowClick);
// Hide the popup
popup.style.display = "none";
});
}, delay);
}
});
#popup {
display: none;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: yellow;
padding: 1em;
}
#thecounter {
float: right;
background-color: rebeccapurple;
padding-top: 50px;
padding-bottom: 50px;
width: 10%;
margin-right: 10px;
font-size: 30px;
color: white;
text-align: center;
}
#thetime {
float: right;
background-color: rosybrown;
padding-top: 50px;
padding-bottom: 50px;
width: 10%;
font-size: 30px;
color: white;
text-align: center;
}
#num4 span {
font-size: 20px;
display: block;
margin-bottom: 4px;
padding: 4px;
}
Delay: <input type="text" id="popup-delay" /> <button type="button" id="popup-show">Show</button>
<div id="popup">
<p>I am a popup :-)</p>
<button type="button" id="popup-close">Close</button>
</div>
<div id="container">
<div id="thecounter">
<p id="num2">clicks </p>
<p id="num1">0 </p>
</div>
<div id="thetime">
<p id="num3">time </p>
<p id="num4"> </p>
</div>
</div>
The problem is that you are getting the elements by id before the dom rendered so it always get null value
just change the event listener of the button to a function like below
function onShowClick () {
var popup = document.getElementById("popup");
var input = document.getElementById("popup-delay");
var showButton = document.getElementById("popup-show");
var closeButton = document.getElementById("popup-close");
// get the user input and convert it into a number
var value = parseInt(input.value, 10);
// if the input is not a number
if (isNaN(value)) {
// warn the user
alert("NaN (Not A Number) !");
}
// otherwise
else {
// convert milliseconds to seconds
var delay = value * 1000;
// turn off the click listener on the "Show" button
showButton.removeEventListener("click", onShowClick);
// start the countdown to show the popup
// document.getElementById("num1").innerHTML= counter1;
counter1= counter1+1;
let currDate = Date();
// document.getElementById("num4").innerHTML += "<span>" + currDate + "</span>";
// add new Row
let table = document.getElementById("table");
var tr = document.createElement('tr');
var tdCounter = document.createElement('td');
tdCounter.appendChild(document.createTextNode(counter1))
tr.appendChild(tdCounter)
var tdTime = document.createElement('td');
tdTime.appendChild(document.createTextNode(currDate))
tr.appendChild(tdTime)
table.appendChild(tr)
setTimeout(function () {
// show the popup
popup.style.display = "block";
// turn on the click listener on the "Close" button
closeButton.addEventListener("click", function onCloseClick () {
// turn off the click listener on the "Close" button
closeButton.removeEventListener("click", onCloseClick);
// turn on the click listener on the "Show" button
showButton.addEventListener("click", onShowClick);
// hide the popup
popup.style.display = "none";
});
}, delay);
}
}
and call it on onclick in html for the button like below
<body>
Delay: <input type="text" id="popup-delay" />
<button type="button" onclick="onShowClick()" id="popup-show">Show</button>
<div id="popup">
<p>I am a popup :-)</p>
<button type="button" id="popup-close">Close</button>
</div>
<div id="container">
<table id="table">
</table>
</div>
</body>
the out put like below
Main Page
Pop up Page

Div container to expand with dynamic grid

this is kind of a two parter. I have a dynamic grid composed of divs (.unit) that I'm trying to contain in one larger div (#pallet). The grid increases based on the integer the user gives in a prompt. My question is how do I get the larger div to expand relative to the size of my grid without using absolute positioning? Also the grid isn't ever reduced to the user given value, it only increases. Any help would be much appreciated!
$(document).ready(function() {
var userChoice = 10;
for(var x = 0; x < userChoice; x++) {
for(var y = 0; y < userChoice; y++) {
var unit = $("<div class='unit'></div>");
unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo
}
}
$(".unit").hover(function(){ //jquery selects the "unit" div and issues a function on it to change the css
$(this).css("background-color", "black"); //this is in reference to .unit changing the css to black
});
document.getElementById("reset").onclick = gridReset; //reset is the id of our button, so when it's clicked it will call our function gridReset
function gridReset() { //function grid reset first asks a prompt then stores the user's choice value in a variable and puts it through checks to see if its valid
userChoice = prompt("Between 1 and 64 how big would you like your grid?"); //we put our user choice in the function so as to not call a prompt at the start of the page load AND to store the variable in the scope
if (isNaN(userChoice)) {
alert(userChoice + " is not a number");
}
else if (userChoice >= 65 || userChoice <= 0) {
alert("Choose a number between 1 and 64");
}
else {
$(".unit").empty();
$(".unit").css("background-color", "blue");
for(var x = 0; x < userChoice; x++) { //for loop creates iteration of userChoice
for(var y = 0; y < userChoice; y++) { //for loop creates iteration of userChoice
var unit = $("<div class='unit'></div>"); //creates a variable "unit" = to a jquery div element with a class of unit
unit.appendTo('#pallet'); //puts div "unit" into div "pallet" using appendTo
$(".unit").hover(function(){ //jquery selects the "unit" div and issues a function on it to change the css
$(this).css("background-color", "black"); //this is in reference to
.unit changing the css to black
});
}
}
}
}
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Odin Div Project</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
</head>
<body>
<button id="reset" type="button">Reset Grid</button>
<div id="pallet">
</div>
<script type="text/javascript" src="scripts/jquery-3.2.0.min.js">
</script>
<script type="text/javascript" src="scripts/script.js"> </script>
</body>
</html>
CSS:
#pallet {
position: relative;
left: 425px;
top: 150px;
background-color: black;
height: 440px;
width: 440px;
}
.unit {
position: relative;
background-color: blue;
height: 20px;
width: 20px;
margin: 1px;
display: inline-block;
float: left;
}

Random card/Image using buttonjavascript

I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.

Categories

Resources