Why does this genorater code not work in JavaScript? - javascript

I am trying to create a simple genorator code for a flight simulator. It should genorate four numbers between 0 and 7, and then update the text of a Div.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SG 0.0.0</title>
<script src="index.js"></script>
</head>
<body>
<div id="squawk">0000</div>
<button onclick="genSquawk" id="gen">Genorate Squawk</button>
</body>
</html>
JS:
const div = document.getElementById('squawk')
var num1 = Math.random() * 7;
var num2 = Math.random() * 7;
var num3 = Math.random() * 7;
var num4 = Math.random() * 7;
function genSquawk() {
div.textContent = num1,num2,num3,num4;
}

div.textContent = num1,num2,num3,num4; is not valid syntax. If you want an an array, for instance, you could use [num1, num2, num3, num4]. Since you're updating the node's text content, you likely want to make these numbers a string value to insert into your div element. In that case, there are many ways to make a string from your series of numbers. One way is string concatenation, something like
div.textContent = `${num1}, ${num2}, ${num3}, ${num4}`;

There are a few changes to be made. One is the following line:
<button onclick="genSquawk" id="gen">Genorate Squawk</button>
You are referencing the genSquawk function on the onclick property, not calling it. The correct is:
<button onclick="genSquawk()" id="gen">Genorate Squawk</button>
Now it should trigger the function properly. The second one is: the syntax num1,num2,num3,num4 is not correct, and will cause the code to display only the first num. In order to do so, use string literals: ${num1}, ${num2}, ${num3}, ${num4}.
Finally, I do not know if you want integers or if each of the four numbers could be floats. But I added a function to generate a int number between 0 and 7.
function getRandomArbitrary() {
return Math.floor(Math.random() * 7);
}
function genSquawk() {
const div = document.getElementById('squawk')
var num1 = getRandomArbitrary();
var num2 = getRandomArbitrary();
var num3 = getRandomArbitrary();
var num4 = getRandomArbitrary();
div.textContent = `${num1}${num2}${num3}${num4}`;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SG 0.0.0</title>
<script src="index.js"></script>
</head>
<body>
<div id="squawk">0000</div>
<button onclick="genSquawk()" id="gen">Genorate Squawk</button>
</body>
</html>

Related

JS - I can get the value of input but not compare it

I'm learning JS and I'm trying to create a web game with javascript. The goal is simple: a flag is displayed at random, and the player must guess the name of the country associated with the flag.
The flag is randomly selected and displayed correctly, but I have a problem with the user interaction. I'd like to display "bad answer" in a <p> and if it's correct, display "good answer" (in a <p>), regenerate a flag and start again, indefinitely. The problem is that I can get the user's answer but i can't compare it to real answer and then display true or false.
I would like to know if someone could explain to me what is wrong and correct me please. Here is my code :
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function getVal() {
const inputValue = document.querySelector('input').value;
console.log(inputValue);
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data => data.json())
.then(data => {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
});
if (inputValue != data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-false");
document.getElementsByClassName('result').innerHTML = 'Mauvaise Réponse';
} else if (inputValue == data[randomInt].name.toLowerCase()) {
document.getElementsByClassName('result').class.add("result-true");
document.getElementsByClassName('result').innerHTML = 'Bonne Réponse';
}
}
<!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>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
The reason is because the scope of inputValue is inside the function getVal only.
So in function getData it doesn't know inputValue.
The scope is the perimeter where the variable is known, it could be globally, local to a function, or at other level. It depends where and how you declare the variable.
It's an important thing to understand in most of the computer langage.
Here's a refactored working version with some comments to help clear things out:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if ( inputValue.toLowerCase() !== flag.toLowerCase()) { // <= Lowercasing both input and flag name to avoid case sensitive comparison failures
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
// No need for an else if here:
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
// TIP: Ideally the next function should be split into 2 functions:
// 1) fetchData(), runs once to grab the JSON
// 2) getRandomFlag(), runs on 'Next' click to get a random flag
// without re-fetching the JSON.
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name; // <= Set the value for the newly fetched flag name
});
}
Working demo:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
let flag = "Cambodia"; // <= We need a global variable so that it can be set and accessed inside getVal() and getData()
function getVal() {
const inputValue = document.querySelector('input').value;
//>> Move the flag vs input comparison inside the input event handler:
if(inputValue.toLowerCase() != flag.toLowerCase()) {
// Use `classList` instead of `class` to have access to the add() method
// Use `querySelector` to pick a single element instead of getElementsByClassName which returns a list of elements:
document.querySelector('.result').classList.add("result-false");
document.querySelector('.result').innerHTML = 'Mauvaise Réponse';
} else {
document.querySelector('.result').classList.add("result-true");
document.querySelector('.result').innerHTML = 'Bonne Réponse';
}
}
function getData() {
var json = 'https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/index.json'
fetch(json)
.then(data=>data.json())
.then(data=> {
const randomInt = getRandomInt(data.length);
console.log(data[randomInt]);
var image = document.getElementById("flag");
image.src = data[randomInt].image;
flag = data[randomInt].name;
});
}
<!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>Guess The Flag - </title>
<link rel="stylesheet" href="style.css">
<!-- <script type="text/js" src="app.js"></script> -->
</head>
<body>
<h1>GuessTheFlag</h1>
<div class="flagCanva">
<img width="100" id="flag" src="https://cdn.jsdelivr.net/npm/country-flag-emoji-json#2.0.0/dist/images/KH.svg" alt="">
</div>
<input type="text" name="flagName">
<button type="submit" onclick="getVal()">Je valide</button>
<p class="result"></p><br>
<button onclick="getData()">Next</button>
</body>
</html>
There's a lot of refactoring that we can do (e.g. caching the selected elements, cache the json response to avoid re-fetching the data, removing global variables, etc.) to improve the code, but this is just a good start for a functional code.

how to append an element more then once

I am trying to create a rock paper scissors game and I want to display each player hand using images
in two separated divs but when the random number be the same it shows only 1 image
this is my html
<!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>Game!!</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<div id="container">
<button id="start-btn">enter-name</button>
<div id="players">
<div id="player"></div>
<div id="robot"></div>
</div>
</div>
<script src="javascript/app.js"></script>
</body>
</html>
this is my javascript
const startBtn = document.getElementById('start-btn');
const players = document.getElementById('players');
const player = document.getElementById('player');
const robot = document.getElementById('robot');
/*
* hands
*/
const rockCard = document.createElement('img');
const paperCard = document.createElement('img');
const scissorCard = document.createElement('img');
rockCard.src = "img/rocks.png";
paperCard.src = "img/paper-boat.png";
scissorCard.src = "img/scissors.png";
rockCard.style.width = "100px"
scissorCard.style.width = "100px"
paperCard.style.width = "100px"
let handsArray = [rockCard, paperCard, scissorCard];
/*
* function to create random number
*/
function playerHand(){
random = Math.floor(Math.random() * 3);
player.appendChild(handsArray[random]);
}
function robotHand(){
random = Math.floor(Math.random() * 3);
robot.appendChild(handsArray[random]);
}
playerHand()
robotHand()
that is because same created element can only be appended once in a document. You can use node.cloneNode(true) to achieve that
player.appendChild(handsArray[random].cloneNode(true));
robot.appendChild(handsArray[random].cloneNode(true));
Let me know if this solve your issue ;)

How do I link my html button value with the variables i've created? right now it says logs it as an html object but not by its value

async function run() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
var num1 = document.getElementById("1");
var num2 = document.getElementById("2");
var num3 = document.getElementById("3");
var num4 = document.getElementById("4");
var num5 = document.getElementById("5");
var num6 = document.getElementById("6");
var num7 = document.getElementById("7");
var num8 = document.getElementById("8");
var num9 = document.getElementById("9");
function addtest(num1, num2) {
return num1 + num2;
}
console.log(num1);
await context.sync();
});
}
When I log this it returns this: HTMLButtonElement {}
I want it to log its value of 1.
enter image description here
This is happening because you are only getting the element itself with your current JavaScript code. You should use innerHTML, innerText, or textContent properties to get the value it holds. Please note that all of them return a string, so you should parse their values before using it.
In your case, I believe innerHTML is what best applies. So, this is what you should be doing:
var num1 = parseInt(document.getElementById("1").innerHTML);
Repeat this code for num1 to num9 and you should be good to go.
The innerHTML Property
From W3Schools definition:
The innerHTML property sets or returns the HTML content (inner HTML)
of an element.
The example below can clarify how .innerHTML works a bit better:
// From your example:
var num1 = document.getElementById('1').innerHTML;
console.log("<button> holds:", num1);
// From other use cases
let h = document.querySelector('#heading').innerHTML;
let p = document.querySelector('#paragraph').innerHTML;
console.log('<h1> holds: ', h) ;
console.log('<p> holds: ', p);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>innerHTML Example</title>
</head>
<body>
<!-- Your example -->
<button id="1">1</button>
<!-- Other use cases -->
<h1 id="heading">This is a heading</h1>
<p id="paragraph">This is a paragraph</p>
</body>
</html>
Refer to HTML DOM innerHTML Property on W3Schools for more information.
Try this
function addtest(num1, num2) {
return parseInt(num1.textContent) + parseInt(num2.textContent);
}

Javascript hit counter

I have just started learning Javascript, and I attempted to write code for hit counter for a webpage using Javascript. I know that we have to use cookies to get the correct number and use PHP to modify data stored in servers. But could you please debug this for me ? I'm getting the output as "The number of visitors is: NaN"
This is my code:
<!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">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = counter.value;
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You are trying to get the valuefrom a span element, which is wrong.
Your counter.value is undefined so it will give you the wrong answer.
You can get the 0 from the span by using document.getElementById("cntr").innerHTML. But the value returned is in string. So you need to do parseInt to convert it into integer and only then your addition will give you the correct value.
<!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">
<title>Document</title>
</head>
<body>
<div>
<p>The number of visitors is : <span id="cntr">0</span></p>
</div>
<script>
function counter_fn() {
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.innerHTML);
count = count + 1;
counter.innerHTML = count;
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to use parseInt
<script>
function counter_fn(){
var counter = document.getElementById("cntr");
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
UPDATE
As #Anurag Singh Bisht commented, you cannot get value from a span element . So to get value from <span> you need to use $('span').text();
<html>
<body>
<div id="cntr">
The number of visitors is :
<span>0</span>
</div>
<script>
function counter_fn(){
var counter = $('#cntr span').text(); // geting value from span
var count = 0;
count = parseInt(counter.value);
count = count+1;
counter.innerHTML = parseInt(count);
}
window.onload = counter_fn;
</script>
</body>
</html>
You need to parse the string to an integer and you need to get the innerHTML.
<script>
function counter_fn(){
var counterElement = document.getElementById("cntr")
var counterNumber = parseInt(counterElement.innerHTML)
counterNumber = counterNumber + 1
counterElement.innerHTML = counterNumber
}
window.onload = counter_fn;
</script>
The correct way to do it would be storing this value somewhere else, like localStorage and reading it from there. You are not supposed to read your own HTML to update the value. HTML elements are supposed to be results, not your input.
var counterNumber = 1
if (localStorage.getItem("count")) {
counterNumber = parseInt(localStorage.getItem("count")) + 1
}
else {
localStorage.setItem("count", counterNumber)
}

JavaScript simple function doesn't return anything

I' m new to JavaScript and am writing a function which has to calculate circle area. But the problem here is that I don't fully understand the concept of functions. So here is my Html code where i have 2 div elements with specific ID. I want my function to take the innerHTML from the first div and according to the given formula int the function to output the result into the second div. Can you help me cause maybe I make some huge error inhere.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Circle Area</title>
<meta charset="utf-8" />
</head>
<body>
<div id="area">7</div>
<div id="output"></div>
<script type="text/javascript" src="circle-area.js"></script>
</body>
</html>
And here is my Js file
function calcCircleArea(r, formula) {
r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = formula;
You have to call the function
function calcCircleArea() {
var r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = calcCircleArea();
FIDDLE
You don't need argument in the function as you are not passing any parameters to the function. You need to call the function. Change your javascript to:
function calcCircleArea() {
r = document.getElementById("area").innerHTML;
var formula = Math.PI * (r * r);
return formula;
}
document.getElementById("output").innerHTML = calcCircleArea();
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Circle Area</title>
<meta charset="utf-8" />
<script>
// There is no need to declare argument variables once again
// Besides, it's better to get radius from outside, i.e. from function call
function calcCircleArea(r) {
return Math.PI * (r * r);
}
</script>
</head>
<body>
<div id="area">7</div>
<div id="output"/>
<script>
document.getElementById("output").innerHTML = calcCircleArea(document.getElementById("area").innerHTML);
</script>
</body>
</html>
<html>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
enter code here
</html>
This is a simple example for use script inside the html file.
It may helps.

Categories

Resources