Javascript innerhtml Display - javascript

Hi I made a js script for coin tossing and when I press the button to start it nothing appears
<script>
var coin = Math.random();
if(coin <= 0.5){
return "H";
}
else{
return "T";
}
var coinFlip = function(){
document.getElementById("flip").innerHTML = coin;
}
</script>
This is the button
<button onClick="coinFlip()">Flip</button>
Thank you for reading

coin is a random number the return is not doing what you think.
var coinFlip = function() {
var coin,
chance = Math.random();
if (chance <= 0.5) {
coin = "H";
} else {
coin = "T";
}
document.getElementById("flip").innerHTML = coin;
}
document.getElementById("btn").addEventListener("click", coinFlip);
<div id="flip"></div>
<button id="btn">Flip</button>

Related

Why the button is not working when function is used in another function in javascript?

I am learning DOM from udemy and stuck here without any hint that why when I am formatting my code and trying to use a function in event listener function value then it stops working.
This is the original Code
let secretNumber = Math.round(Math.random() * 99) + 1;
let score = 20;
let highscore = 0;
document.querySelector(".check").addEventListener("click", function () {
const guess = Number(document.querySelector(".guess").value);
//Main Function used for DOM queryselection
const displayFunct = function (className, message) {
document.querySelector(className).textContent = message;
};
//When there is no input
if (!guess) {
displayFunct(".message", "No Value๐Ÿฎ๐Ÿฎ๐Ÿฎ๐Ÿฎ๐Ÿฎ");
}
//When player Wins
else if (guess === secretNumber) {
displayFunct(".message", "Correct Number ๐Ÿ˜Ž๐Ÿ˜Ž๐Ÿ˜Ž");
document.querySelector("body").style.backgroundColor = "#60b347";
document.querySelector(".number").style.width = "30rem";
if (score > highscore) {
highscore = score;
}
displayFunct(".highscore", highscore);
}
// When guess is wrong
else if (guess !== secretNumber) {
if (score > 1) {
displayFunct(".message", guess > secretNumber ? "Too HIGH" : " Too LOW");
score--;
displayFunct(".score", score);
} else {
displayFunct(".message", "You Lose!!!!");
displayFunct(".score", 0);
}
}
});
//Coding Challenge 1
document.querySelector(".again").addEventListener("click", function () {
secretNumber = Math.round(Math.random() * 99) + 1;
score = 20;
//Messages Default
document.querySelector(".number").textContent = "?";
document.querySelector(".message").textContent = "Start guessing...";
document.querySelector(".score").textContent = score;
document.querySelector(".guess").value = "";
//CSS Default
document.querySelector("body").style.backgroundColor = "#222";
document.querySelector(".number").style.width = "15rem";
});
In the Coding Challenge 1 section under Message default whenever I am using DisplayFunc()
instead of first 3 code lines then again button stops resetting my code.
This is how I want it to be but It is not happening.
//Coding Challenge 1
document.querySelector(".again").addEventListener("click", function () {
secretNumber = Math.round(Math.random() * 99) + 1;
score = 20;
//Messages Default
DisplayFunc("number", "?" )
DisplayFunc(".message", "Start guessing..." )
DisplayFunc(".score",score)
document.querySelector(".guess").value = "";
//CSS Default
document.querySelector("body").style.backgroundColor = "#222";
document.querySelector(".number").style.width = "15rem";
});
The problem is the location of your displayFunct.
You defined it inside document.querySelector(".check").addEventListener("click", function () { but you are trying to use it inside another function document.querySelector(".again").addEventListener("click", function () {.
That will never work.Move it outside the first function and both functions will be able to use it.
In the second function you are calling DisplayFunc instead of displayFunct, so that's also wrong.
let secretNumber = Math.round(Math.random() * 99) + 1;
let score = 20;
let highscore = 0;
//Main Function used for DOM queryselection
const displayFunct = function (className, message) {
document.querySelector(className).textContent = message;
};
document.querySelector(".check").addEventListener("click", function () {
...

Javascript high score update regardless of whether new score is higher or not

Newbie here! Apologies if I have not formatted this correctly.
I have a whack-a-mole game and want to keep score in local storage. The function at the bottom called 'highscore' is not working - it updates the 'highscore' regardless of whether it is in fact higher than the previous score or not!
I'm sure I'm missing something super obvious, like I say, very new to this! Only using Vanilla Javascript at this stage so hints or solutions in keeping would be ideal.
Any help or pointers in the right direction much appreciated!
Thank you!
window.onload = function() {
setUp();
count = 0;
myDiv = document.getElementById("mole");
myDiv.addEventListener("click", function() {});
};
function setUp() {
let img = document.createElement("img");
img.src = "mole.png";
img.onclick = function(event) {
whackedMole();
};
img.className = "mole";
img.id = "mole";
document.getElementById("moleMap")
.rows[randomNumber()].cells[randomNumber()].appendChild(img);
}
function randomNumber() {
return Math.floor(Math.random() * 5);
}
function whackedMole() {
let mole = document.getElementById("mole");
let audio = new Audio('whack-audio.wav');
audio.play();
document.getElementById("counter").innerHTML = (++count);
mole.parentNode.removeChild(mole);
setUp();
}
let myTimer = 0;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 10;
function myClock() {
document.getElementById("countdown").innerHTML = --c;
if (c <= 0) {
clearInterval(myTimer);
alert("Your score is " + count + "!");
highscore();
document.getElementById("counter").innerHTML = 0;
count = 0;
}
}
}
//This is the function in question;
function highscore() {
document.getElementById("highscore").innerHTML = count;
let highscore = count;
if (count <= highscore) {
return;
} else if (count > highscore) {
localStorage.setItem('highscore', count);
}
}
If i understood correctly the problem lies in this code:
function highscore() {
document.getElementById("highscore").innerHTML = count;
let highscore = count;
if (count <= highscore) {
return;
} else if (count > highscore) {
localStorage.setItem('highscore', count);
}
}
and specifically on these two lines:
document.getElementById("highscore").innerHTML = count;
and
let highscore = count;
Everytime you call highscore(); you are updating your DOM regardless of if the count is > than the highscore. Then on the second line of code that i have hinted highscore gets the value of count so the first statement in the if clause will always evaluate to true. What i would do is modify the code as following:
function highscore() {
// Just in case the highscore is not yet initialized.
if (!localstorage.getItem('highscore')) {
localstorage.setItem('highscore', count);
}
let highscore = localstorage.getItem('highscore');
if (count <= highscore) {
return;
} else if (count > highscore) {
document.getElementById("highscore").innerHTML = count;
localStorage.setItem('highscore', count);
}
}

setting a localstorage high score and displaying it

I have a tetris game that I am trying to finish but saving the high score after a game is over is causing me some issues. When the game ends, if the score is higher than what was previously saved as a highscore, it is supposed to save that new score as the high score locally and display that new highscore. I can not figure out why this is not happening. Below are the three different areas of my code that pertain to the high score. Any help would be appreciated.
creates the menu on the side of the game
<div id="tetris">
<div id="menu">
<p id="start">Press Space to Play.</p>
<p><canvas id="upcoming"></canvas></p>
<p>score <span id="score">00000</span></p>
<p>rows <span id="rows">0</span></p>
<p>high score <span id="highscore">0</span></p>
</div>
<canvas id="canvas">
Sorry, this example cannot be run because your browser does not support the <canvas> element
</canvas>
sets the high score when the game is over
var highscore = localStorage.getItem("highscore");
if (playing == false){
if(highscore !==null){
if(vscore > highscore) {
localStorage.setItem("highscore", vscore);
}
}
else{
localStorage.setItem("highscore", vscore);
}
}
else{
null;
}
updates the scores to display them
function play() { hide('start'); reset(); playing = true; }
function lose() { show('start'); setVisualScore(); playing = false; }
function setVisualScore(n) { vscore = n || score; invalidateScore(); }
function setScore(n) { score = n; setVisualScore(n); }
function addScore(n) { score = score + n; }
function clearScore() { setScore(0); }
function clearRows() { setRows(0); }
function setRows(n) { rows = n; step = Math.max(speed.min, speed.start - (speed.decrement*rows)); invalidateRows(); }
function addRows(n) { setRows(rows + n); }
function setHighScore(n) { highscore = n; }
function addHighScore(n) { setHighScore(highscore); }
function getBlock(x,y) { return (blocks && blocks[x] ? blocks[x][y] : null); }
function setBlock(x,y,type) { blocks[x] = blocks[x] || []; blocks[x][y] = type; invalidate(); }
function clearBlocks() { blocks = []; invalidate(); }
function clearActions() { actions = []; }
function setCurrentPiece(piece) { current = piece || randomPiece(); invalidate(); }
function setNextPiece(piece) { next = piece || randomPiece(); invalidateNext(); }
function reset() {
dt = 0;
clearActions();
clearBlocks();
clearRows();
clearScore();
setCurrentPiece(next);
setNextPiece();
}
function update(idt) {
if (playing) {
if (vscore < score)
setVisualScore(vscore + 1);
handle(actions.shift());
dt = dt + idt;
if (dt > step) {
dt = dt - step;
drop();
}
}
}
I can add the full game code if needed but these are the three areas that directly pertain to the high score issue.
Try the following:
function update(idt) {
if (playing) {
if (vscore < score)
setVisualScore(vscore + 1);
handle(actions.shift());
dt = dt + idt;
if (dt > step) {
dt = dt - step;
drop();
}
// Add the following to update the highscore while playing.
if (score > highscore) {
setHighScore(score);
}
}
}
setHighScore = (score) => {
// update highscore
highscore = score;
// update it visually?
document.getElementById('highscore').text = highscore;
}
Then somewhere you'd want a check once the game is over -- I'd assume immediately where you set the playing boolean to false.
if (playing === false){
if(vscore > highscore) {
// For future games.
localStorage.setItem("highscore", vscore);
}
}
edit :
I'm typing this on my phone, so apologies if format is wonky.
See example : https://codepen.io/anon/pen/pVEJJW

Wait for a timer to complete before seeing the result

I want to get the timer first, then see the result. When I open the page, and start the function war() it shows the result, then it shows the cooldown in the set color. I want to get the cooldown first, then the result.
JavaScript:
var points = 100;
function war() {
var dealer = document.getElementById("dealer");
var player = document.getElementById("player");
var winner = document.getElementById("winner");
var winner1 = document.getElementById("winner");
var screen = document.getElementById("points");
var dealercard = Math.floor(Math.random() * 10) + 1;
var playercard = Math.floor(Math.random() * 10) + 1;
dealer.innerHTML = dealercard;
player.innerHTML = playercard;
var skaiciuoklis = 5;
var naujaselemnt = document.createElement("p");
naujaselemnt.innerHTML = "Wait... 5 seconds.";
var idwar;
dealer.parentNode.replaceChild(naujaselemnt, dealer);
idwar = setInterval(function() {
skaiciuoklis--;
if (skaiciuoklis < 0) {
winner1.parentNode.replaceChild(dealer, naujaselemnt);
clearInterval(idwar);
} else {
winner1.innerHTML = "Wait... " + skaiciuoklis.toString() + " seconds.";
}
}, 500);
if (dealercard > playercard) {
winner.style.color = "red";
winner.innerHTML = "You lost 20 points";
} else {
winner.style.color = "green";
winner.innerHTML = "You won 10 points!";
}
if (dealercard == playercard) {
winner.style.color = "blue";
winner.innerHTML = "WAR. You won 20 points!"
}
if (dealercard < playercard) {
points = points + 10;
screen.innerHTML = points;
}
if (dealercard == playercard) {
points = points + 20;
screen.innerHTML = points;
}
if (dealercard > playercard) {
points = points - 20;
screen.innerHTML = points;
}
if (points <= 0) {
winner.style.color = "red";
winner.innerHTML = "Game Over";
alert("Game Over. REFRESH PAGE TO RETRY!");
points = 100;
}
You can use ES6 async await and move your timer to a separate function outside. You have a lot of variables and it isn't so clear but it looks like your timer is in the function war(). Javascript is asynchronous and it will move to next code even if you have a timer.
An example like this:
function timer(){
// implement timer
}
async function war() {
// at the line u want to call the timer
await timer();
}

where do i place NaN code?

Here is a new question. I want to make my Nan say "this is not a number" if nothing or text is entered. I know the physical code but I dont know where to put it or if I must make a function. Where ever I put it it either loops and say what ever was inputted first and then then "this is not a number" or "this is not a number" then NaN or it doesn't work at all.
javacript:
window.onload = function (){
var myDiv = document.getElementById("wrapper");
wrapper.setAttribute("align","center");
var startButton = document.getElementById("start");
var pauseButton = document.getElementById("pause");
var secondsBlock = document.getElementById("seconds");
var timer = document.getElementById("timer");
var newTime = document.createElement("h1");
newTime.innerHTML = secondsBlock.value;
timer.appendChild(newTime);
//setTimeout(function countdown () {
var numbers = (newTime.innerHTML);
newTime.innerHTML = numbers;
var newNumber;
function countdown(count){
newNumber =secondsBlock.value;
var numbers = (newNumber);
newTime.innerHTML = numbers;
stopper = setInterval(reduceAndShow, 1000);
if (numbers <10){
newTime.style.color = "red";
newTime.innerHTML = "0" + numbers;
};
};
function reduceAndShow(){
newNumber--;
var numbers = (newNumber);
newTime.innerHTML = numbers;
stopCountdown();
if (newNumber <10){
newTime.style.color = "red";
newTime.innerHTML= "0" + newNumber;
};
};
function stopCountdown(){
if(newNumber <= 0){
clearInterval(stopper);
};
};
startButton.onclick = function(){
countdown();
};
function pauseBut(){
clearInterval(stopper);
};
pauseButton.onclick =function(){
pauseBut()
};
html:
<div id="wrapper">
Seconds: <input type="text" name= "seconds" id="seconds"> <input type="button"
value="Start" id="start"> <input type="button" value="Pause" id="pause">
<div id="extraText"></div>
<div id="timer"></div>
</div>
You should get your example running in JSFiddle.net so people can see the whole thing, and investigate for you why it isn't working.
Here's one I made for you.
I've changed your code to the below. The main difference is I split it into two functions. One which checks that the input is a valid number, and the other does the counting down / displaying. One other little thing I changed was the way you declared the countdown function, you sort of declared it twice, I've changed it so it's only declared once:
window.onload = function(){
var myDiv = document.getElementById("wrapper");
var startButton = document.getElementById("start");
va r pauseButton = document.getElementById("pause");
var secondsBlock = document.getElementById("seconds");
var timer = document.getElementById("timer");
var newTime = document.createElement("h1");
function countdown(count) {
newTime.innerHTML = count;
if (count < 10) {
newTime.style.color = "red";
};
timer.appendChild(newTime);
if (count > 0) {
setTimeout(function () {
countdown(count - 1);
}, 1000);
}
}
function testInput() {
var count = seconds.value;
if (count == "" || isNaN(count)) {
newTime.innerHTML = "This is not a number";
timer.appendChild(newTime);
} else if (count > 100) {
newTime.innerHTML = "Number must be between 0 and 99"
timer.appendChild(newTime);
} else {
countdown(count);
}
}
startButton.onclick = testInput;
}
Looks like a very simple case of
if (typeof(seconds.value) == "number") { newTime.innerHTML = seconds.value; }
else { newTime.innerHTML = "This is not a number"; }
timer.appendChild(newTime);

Categories

Resources