How can I use JavaScript to grab a random div? - javascript

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/

Related

Why isn't the input box outputting the correct response

When the user clicks the buttons I want it to output the correct response.If the user puts 0 in the input box and then clicks the button I want it to say this is zero.If it 1 and higher I want it to say it positive number.If it -1 and lower it should say this is negative number.
<!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>numberCheck</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<h1>Number Check</h1>
<input type="number" id="num">
<button id="submit">Submit</button>
<div id="store"></div>
<script>
const num = document.getElementById('num');
const data = num.value
const btn = document.getElementById('submit');
const store = document.getElementById('store');
btn.addEventListener('click',()=>{
checker();
});
function checker(){
const ele = document.createElement('div');
if (data === 0){
ele.innerHTML =data+' this is a zero';
store.appendChild(ele);
}
if (data <0){
ele.innerHTML =data+' this is a negitive number';
store.appendChild(ele);
}
if (data >0){
ele.innerHTML =data+' this is a positive number';
store.appendChild(ele);
}
}
</script>
</body>
</html>
> const ele = document.createElement('div');
> if (num === 0){
> ele.innerHTML =num+' this is a zero';
> store.appendChild(ele);
> }
You try to refer to the HTML element and compare it to zero. It's not. What you have to do is to check if the value of the input matches to your condition.
if (num.value == 0)
By the way, don't use triple equals here. The input value is always a string, but you compare it against a number, so "===" will always return a false here. Either explicitly convert input's value to a type of number or use double equals.
So first do not repeat yourself, if you want to create a new div and append it i'll recommend u to do it once in your function.
const ele = document.createElement('div');
store.appendChild(ele);
and because you are using input type number u have to get the value as integrer with valueAsNumber.
Then you have to update the value, yes because the value change while u are loading the value but never updating it.
By the way for a changing value u can't use const but need to use a let or var.
btn.addEventListener('click', function() {
let val = num.valueAsNumber;
checker(val);
});
Here is a working version of your code : https://jsfiddle.net/4a17fsbn/
You write far too much code and your code is inefficient.
The main issue is, that the value of an input type="number"is not necessarily an integer. As soon as you write into the input with a keyboard then you get a string. To solve this you simply need to add a + before the string which converts it to an integer: +document.querySelector('#num').value.
As said above, your code is inefficient. One efficiency boost you can gain with textContent instead of using innerHTML which requires a re-parsing of the DOM. Then only write the actual necessary code and combine the eventListener with the function directly.
document.querySelector('#submit').addEventListener('click', function() {
let nr = +document.querySelector('#num').value,
el = document.querySelector('#store');
if (nr === 0) {
el.textContent = `${nr} this is a zero`;
}
if (nr < 0) {
el.textContent = `${nr} this is a negative number`;
}
if (nr > 0) {
el.textContent = `${nr} this is a positive number`;
}
})
<h1>Number Check</h1>
<input type="number" id="num">
<button id="submit">Submit</button>
<div id="store"></div>
you can use change event and get the value as per entered by the user
const inputField = document.getElementById("num");
let num = 0;
inputField.addEventListener("change", (e) => {
num = +e.target.value;
});
btn.addEventListener("click", () => {
checker(num);
});
function checker(num) {
const ele = document.createElement("div");
console.log(num);
if (num === 0) {
ele.innerHTML = num + " this is a zero";
store.appendChild(ele);
}
if (num < 0) {
ele.innerHTML = num + " this is a negitive number";
store.appendChild(ele);
}
if (num > 0) {
ele.innerHTML = num + " this is a positive number";
store.appendChild(ele);
}
}
or you can more simplify the code
btn.addEventListener("click", () => {
checker(+inputField.value);
});

I have trouble hiding elements in my game if they don't match

I am working on a memory game and I asked a previous question earlier which was answered. I've had this problem and I haven't been able to find a solution with effort. So it's a memory game and when the cards are clicked, they are pushed into an array which can hold two elements at max (you can only click two cards) and then the two elements' frontSrc is checked if they are the same. I set that using an expando property. If so, have them visible and then clear the array so I can do more comparisons. However, it doesn't seem to be working as intended. I'll attach a video below. I've tried using timeout to set the length again, but that didn't work. It works for the first cards, but the other ones after that, it doesn't work.
Here is my code.
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{
width: 35%;
}
#cards{
display: grid;
grid-template-columns:25% 25% 25% 25%;
row-gap: 25px;
}
</style>
</head>
<body onload="init()">
<section id="cards">
</section>
<script>
var arrCards = [];
var arrShowedCards = [];
//appendElements();
function init(){
createCards();
shuffleCards();
appendElements();
}
function createCards(){
var arrCardNames = ["Mouse","Penguin","Pop","Mouse","Penguin","Pop"];
for(var i = 0; i<6; i++){
var card = document.createElement("IMG");
card.src = "Images/red_back.png";
card.className = "card";
card.frontSrc = "Images/" + arrCardNames[i] + ".png";
card.id = "card" + i;
card.addEventListener("click", showCard);
document.getElementById("cards").appendChild(card);
arrCards.push(card);
}
}
function shuffleCards(){
for (let i = arrCards.length-1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
const temp = arrCards[i];
arrCards[i] = arrCards[j];
arrCards[j] = temp;
}
return arrCards;
}
function appendElements(){
for(var i = 0; i<arrCards.length; i++){
document.getElementById("cards").appendChild(arrCards[i]);
}
}
function showCard(){
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if(arrShowedCards.length === 2){
if(arrShowedCards[0].frontSrc === arrShowedCards[1].frontSrc){
console.log("Match!");
arrShowedCards = [];
}
else{
console.log("No match!");
setTimeout(function(){
arrShowedCards[0].src = sourceString;
arrShowedCards[1].src = sourceString;
}, 1000);
}
}
}
</script>
</body>
</html>
I am not sure how come it doesn't work for it for the other cards.
Here is the video.
https://drive.google.com/file/d/1aRPfLALHvTKjawGaiRgD1d0hWQT3BPDQ/view
If anyone finds a better way to approach this, let me know.
Thanks!
I think when not match, you need to reset arrShowedCards otherwise its length will be greater than 2 forever.
function showCard() {
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if (arrShowedCards.length === 2) {
var a = arrShowedCards[0], b = arrShowedCards[1];
arrShowedCards.length = 0;
if (a.frontSrc === b.frontSrc) {
console.log("Match!");
} else {
console.log("No match!");
setTimeout(function () {
a.src = sourceString;
b.src = sourceString;
}, 1000);
}
}
}

How can I reset time in a simple game?

I've tried make simple clicking game (if time count is higher than 5, the game is over, but you can reset time if you click generated element).
Unfortunately time is still counting. How can I fix this?
Why do I get this error?
Uncaught TypeError: Cannot set property 'textContent' of null
at js.js:8
at js.js:49
(function() {
const startGame = document.querySelector('button')
let time = 0;
let roll = true;
let h2 = document.querySelector('h2')
h2.textContent = time;
const timeFlow = () => {
time++
}
const resetTime = () => {
time = 0;
console.log(time)
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square')
divCreator.style.backgroundColor = 'red'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
setInterval(timeFlow, 1000)
} else if (roll == false) {
roll = true;
}
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<script src='js.js'></script>
<h2>Time</h2>
</body>
</html>
You can use the load event instead of an IIFE before the elements exist.
Also your div needs dimensions
Also I assume you want the time in the H2?
Also you need position absolute to move the div
Lastly I clear the interval before a new one
window.addEventListener("load", function() {
const startGame = document.querySelector('button')
const h2 = document.querySelector('h2')
let tId;
let time = 0;
let roll = true;
h2.textContent = time;
const timeFlow = () => {
time++
h2.textContent = time;
}
const resetTime = () => {
time = 0;
}
const rollBall = () => {
if (roll == true) {
let divCreator = document.createElement('div')
document.body.appendChild(divCreator)
divCreator.classList.add('square');
divCreator.style.height = '50px'
divCreator.style.width = '50px'
divCreator.style.backgroundColor = 'red'
divCreator.style.position = 'absolute'
divCreator.style.top = Math.floor(Math.random() * 99) + '%'
divCreator.style.left = Math.floor(Math.random() * 99) + '%'
divCreator.addEventListener('click', letsPlay)
divCreator.addEventListener('click', resetTime)
clearInterval(tId); // remove any running interval
tId = setInterval(timeFlow, 1000)
}
roll = !roll;
}
const letsPlay = (e) => {
let start = document.body.removeChild(e.target)
roll = false;
if (time >= 5) {
alert('U lost')
} else {
roll = true; // right?
rollBall()
}
}
startGame.addEventListener('click', rollBall)
})
body {
height: 100%;
background-color: yellow;
}
<button>Generate</button>
<h2>Time</h2>
Your HTML code is in the wrong order: the <h2> element and the <script> element should be switched.
You should change it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button>Generate</button>
<h2>Time</h2>
<script src='js.js'></script>
</body>
</html>

How to update a JavaScript generated HTML variable

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);

executing the wrong function in if statement

/*
GAME FUNCTION:
- player must guess a number beetween min and max
- player gets a certain amount of guesses
- notify player of guesses remaining
- notify the player with a correct number if he loose
- let player choose to play again
*/
// variabels
//game values
let min = 1,
max = 10,
winningNum = 2,
guessesLeft = 3;
// UI elements
const game = document.getElementById('game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessBtn = document.getElementById('guess-btn'),
guessInput = document.getElementById('guess-input'),
message = document.querySelector('.message');
// assign ui min and max
minNum.textContent = min;
maxNum.textContent = max;
// event listener
function loadEventListener() {
// listen for guess
guessBtn.addEventListener('click' , checkGuess );
};
loadEventListener();
// checks the entered number
function checkGuess() {
let guess = parseInt(guessInput.value);
//validate the input
if(isNaN(guess) || guess < min || guess > max ) {
console.log('here')
/////// this below code setMessage is not executing when the condintions are true.. ////
setMessage(`Please enter a number between ${min} and ${max}` , 'red');
console.log('here again')
};
//check if won
if(guess === winningNum) {
// right case here
//dsiabe input
guessInput.disabled = true;
// change border color
guessInput.style.borderColor = 'green';
// set message
setMessage(`${winningNum} is correct.. you WON the game!!` , 'green');
} else {
// wrong case here
guessesLeft -= 1;
if(guessesLeft === 0) {
// game over - lost
// disable input
guessInput.disabled = true;
// change border color
guessInput.style.borderColor = 'red';
// set message
setMessage(`Game over..! The correct Number was ${winningNum}..` , 'red');
} else {
// game continues - answer wrong
// change border color
guessInput.style.borderColor = 'red';
// clear input
guessInput.value = '';
// tell user its the number
setMessage(`${guess} is not Correct,${guessesLeft} guesses left.` , 'orange')
};
}
};
// set message
function setMessage(msg , color) {
message.style.color = color;
message.textContent = msg;
}
<!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="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" />
<title>Number Guesser</title>
</head>
<body>
<div class="container">
<h1>Number Guesser</h1>
<div id="game">
<p>Guess a number beetween
<span class="min-num"></span>
and
<span class="max-num"></span>
</p>
<input type="number" name="" id="guess-input" placeholder="Enter Your Guess...">
<input type="submit" value="submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
when i click on the submit button without entering the values, the function in line 49 setMessage should execute, but its executing the code of 82nd line.., it should display the message (message placed in the argument) in 49th line code but its showing message from 82nd line.. please look at the issue..what else is wrong in the code???
Your problem is that you don't exit the checkGuess() function when it fails validation.
If you add a return; after the failed validation error is shown then it will solve your issue...
function checkGuess() {
let guess = parseInt(guessInput.value);
//validate the input
if(isNaN(guess) || guess < min || guess > max ) {
setMessage(`Please enter a number between ${min} and ${max}` , 'red');
return; // exit the function here, since we've failed validation
};

Categories