How to reuse a function without refreshing the page - javascript

When i use the function to check if number is positive or negative it works fine but when i try to do it again nothing happens i have to refresh the whole page to make it work again. Any help is welcome!
const userNum = document.querySelector(".user-input").value;
const checkBtn = document.querySelector(".check-input");
const result = document.querySelector(".result");
function checkNum() {
if (userNum > 0) {
result.innerHTML = "Positive!!"
}
else if (userNum < 0) {
result.innerHTML = "Negativeee!!"
}
else if (userNum < 0) {
result.innerHTML = "Number is NULL"
}
else {
result.innerHTML = "Enter a Number!!"
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<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>Document</title>
</head>
<body>
<div class="container">
<div class="intro">
<h1>A Program to Check if number is <br></h1>
<h2>Positive, Negative or Null</h2>
</div>
<div class="check-number-type">
<input type="text" class="user-input">
<button onclick="checkNum()" class="check-input">Check</button>
</div>
<div class="show-result">
<p class="result"></p>
</div>
</div>
</body>
<script src="/script.js"></script>
</html>

The reason why you say you have to "reload" the page everytime is because your code that extracts the input value was placed outside of your checkNum function that determines if it's positive or negative.
You only retrieve the input once, when the script starts, instead of getting a fresh copy everytime you enter the checkNum function.
Just move this:
const userNum = document.querySelector(".user-input").value;
Inside the checkNum() function.

Related

Grid of Textareas Does Not Display

I have been trying to make a wordle copy where the amount of guesses and word length can be controlled. So I used a nested for loop to display the grid. My school has banned inspect on my computer so I cannot use console.log. The error might be coming from the fetch request. I hope I get an answer soon.
<!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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<title>Unlimited Wordle</title>
</head>
<body>
<center><h1>Unlimited Wordle</h1><br><br>
<h4>Start out by tying in word length and amount of guesses. (Defaults are 5 and 6)</h4>
<h3>Word Length:</h3>
<input id="length"/>
<h3>Guesses:</h3>
<input id="width"/><br><br>
<button id="start" onclick="play()">Start!</button>
<div id="grid"></div><br><br>
<button id="new" onclick="location.refresh()"><h4>Get A New Word!</h4></button><br><br>
<h3 id="answer"></h3></center>
<script>
function play(){
grid=document.getElementById("grid");
var line=1;
if(document.getElementById("width").length==0){
var width=5;
}else{
var width=parseInt(document.getElementById("width").value);
}
if(document.getElementById("length").length==0){
var length=6;
}else{
var length=parseInt(document.getElementById("length").value);
}
var length=parseInt(document.getElementById("length").value);
var word="";
while(length(word)!=width){
word=fetch("https://random-word-api.herokuapp.com/word");
}
for (i=0; i<length; i++){
for(j=0; j<width; j++){
grid.innerHTML+=`<textarea id="${i} ${j}" rows="1", cols="1" maxlength="1" style="resize: none;" onkeyup="this.value = this.value.toUpperCase(); "></textarea>`
}
grid.innerHTML+="<br>"
}
window.addEventListener(onkeydown, function(event){
var typed="";
if(event.keyCode==13){
var filled=true;
var colors="";
for(k=1; k<width; k++){
typed+=document.getElementById(`${line} ${k}`).value
if(document.getElementById(`${line} ${k}`).value.length==0){
var filled=false;
}
}
if(filled==true){
for(k=1; k<width; k++){
if(word[i]==typed[i]){
document.getElementById(`${line} ${k}`).style.color="green";
}
if(word.includes(typed[i])){
document.getElementById(`${line} ${k}`).style.color="yellow";
}
if(!word.includes(typed[i])){
document.getElementById(`${line} ${k}`).style.color="gray";
}
document.getElementById(`${line} ${k}`).readOnly=true;
}
line++;
if(line>6){
document.getElementById("answer").innerHTML=`The word was: ${word}.`;
}
}
}
}
)
}
</script>
</body>
</html>
My github is https://github.com/ethanreesewagner.

number value return NaN in js

in this excercise i create a counter that has a number display and 2 button to lower and increase number. i assign number to parseInt(num) to convert num object to number. i use alert to check type of number. typeof(number) return number but number return NaN. please someone explain.[edit]reading comment, i was able to solve the problem. i have upadated the solution
var low = document.getElementById("low")
var add = document.getElementById("add")
low.addEventListener("click", function () {
var num = document.getElementById("num")
var number = parseInt(num.innerText)
num.innerHTML = number - 1
})
add.addEventListener("click", function () {
var num = document.getElementById("num")
var number = parseInt(num.innerText)
num.innerHTML = number + 1
})
<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>Document</title>
<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<div class="container">
<h1>counter</h1>
<h1 id="num">0</h1>
<div class="btn">
<button id="low">lower count</button>
<button id="add">add count</button>
</div>
</div>
<script src="js.js"></script>
</body>
</html>
You are trying to parseInt(num) but num is DOM element - not number. You want its content. You can get it with .innerText.
const num = document.getElementById("num")
console.log(num);
console.log(parseInt(num));
console.log(parseInt(num.innerText));
<h1 id="num">0</h1>

addEventLister on a button only works twice and only when window is refreshed

I have two buttons when clicked I want to call functions I wrapped all my function in play() function
I tried to an addEventListener to the guess button but it only runs the alert only twice after the window is refreshed.
function play() {
let numInput = document.getElementById("input-number");
let resultText = document.getElementById("result-text");
let btnReset = document.getElementById("btn-reset");
let btnGuess = document.getElementById("btn-guess");
let numRandom = null;
function getRandomNumber(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
}
function guessTheNumber(){
numRandom = getRandomNumber(1,5);
numInput = numInput.value;
alert("button clicked")
}
btnGuess.addEventListener("click",function (){
guessTheNumber();
});
}
play();
<!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 That Number</title>
<link rel="stylesheet" href="guessthatnumber.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>
<body>
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number"
placeholder="Enter your number here"
tabindex="1" autofocus >
<h4 class="game-result" id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
<script src="guessthatnumber.js"></script>
</body>
</html>
It is happening because you are changing numInput value every time button is pressed..
numInput = numInput.value;
first iteration:
numInput is equal to value inside an input (lets say it is 5)
so the numInput is 5
second iteration:
numInput is equal to numInput.value and since 5 does not have .value attribute, it is undefined and you get error
The issue with the code is in guessTheNumber function.
You are calculating the random number using numRandom = getRandomNumber(1, 5); and in the next line you are assigning numInput = numInput.value;. Here numInput is your input element. You are overwriting that variable with a number. Next time when guessTheNumber executes numInput will be a string and numInput.value will be undefined. Third time you are trying to access value of undefined, this will throws a console error like Uncaught TypeError: Cannot read properties of undefined (reading 'value')
Correct that code segment to make your code stable.
I have commented that section to make the code not broken.
function play() {
let numInput = document.getElementById("input-number");
let resultText = document.getElementById("result-text");
let btnReset = document.getElementById("btn-reset");
let btnGuess = document.getElementById("btn-guess");
let numRandom = null;
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function guessTheNumber() {
numRandom = getRandomNumber(1, 5);
// numInput = numInput.value;
console.log(numRandom);
alert("button clicked")
}
btnGuess.addEventListener("click", function () {
guessTheNumber();
});
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap"
rel="stylesheet">
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
<h4 class="game-result" id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
Several things
Calling the variable numInput the same as the field is not a good idea and is the main issue in your code
You did not toggle the success
You can simplify the code by moving the functions outside
const numInput = document.getElementById("input-number"),
resultText = document.getElementById("result-text"),
btnReset = document.getElementById("btn-reset"),
btnGuess = document.getElementById("btn-guess");
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function play() {
let numRandom = getRandomNumber(1, 5);
let num = +numInput.value;
resultText.hidden = numRandom != num;
console.log(numRandom === num ? "you guessed right" : "you guessed wrong")
}
btnGuess.addEventListener("click", play)
btnReset.addEventListener("click", function() { resultText.hidden = true; numInput.value = ""; })
<!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 That Number</title>
<link rel="stylesheet" href="guessthatnumber.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght#0,100;0,300;0,400;1,100&display=swap" rel="stylesheet">
</head>
<body>
<main>
<h3 class="game-header">Guess the number!</h3>
<p class="game-instruction">Enter a number between 1 - 5 below:</p>
<input class="game-input" type="text" id="input-number" placeholder="Enter your number here" tabindex="1" autofocus>
<h4 class="game-result" hidden id="result-text">Success!</h4>
<div class="btn-container">
<button class="btn-clear" id="btn-reset">Reset</button>
<button class="btn-guess" id="btn-guess">Guess</button>
</div>
</main>
<script src="guessthatnumber.js"></script>
</body>
</html>

Increase and Decrease of count

I'm trying to create a code that can increase and decrease via clcik of a button
html code but the problem is i cant get it to function I've tried different options.
<!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="styles.css">
<title>Document</title>
</head>
<body>
<div id="body">
<h1>COUNTER</h1>
<span id="time">0</span><br>
<button id="lower" onclick="reduceone()" type="button">LOWER COUNT</button><BR>
<button id="add" onclick="addone()" type="button">ADD COUNT</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="index.js"></script>
</body>
</html>
javascript code:
$("#add").click(function (){
let count = 0;
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
let count = 0;
count --;
$("#time").text(count)
});
Try this
let count = 0;
$("#add").click(function (){
count ++;
$("#time").text(count);
});
$(#lower).click(function(){
count --;
$("#time").text(count)
});
You have to make variable (count ) a global variable so all functions can access his value . If you put variable(count) in a function then only that function can access his value . Hope you understand
You need to share the state between two functions so each of them could see the shared state that they are changing.
Also, all id or class names should be between inverted commas like that "#lower"
let count = 0; // Shared state that both functions can see
$("#add").click(function (){
count++;
$("#time").text(count);
});
$("#lower").click(function(){ // "#lower" not #lower
count--;
$("#time").text(count)
});

Keep body scrolled at the bottom unless user scrolls up in javascript

I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!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 id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) acceptCommand();
setInterval(scrollUpdate, 1000);
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}

Categories