I am trying to make an event when two numbers randomly generated are equal.So I need to store values in a variable in javascript and see if they are equal.
if (target_number == you_score){
console.log(1)
}
I have put console.log in there to test if the statement is executed
const button = document.querySelector('target_number')
function getRandomNumber() {
return Math.floor(Math.random() * 10)
}
function getRandomNumber2() {
return Math.floor(Math.random() * 10)
}
function getRandomNumber3() {
return Math.floor(Math.random() * 10)
}
document.getElementById("target_number").addEventListener("click", displayGuess);
function displayGuess(){
document.getElementById("target_number").innerHTML = getRandomNumber();
}
document.getElementById("target_number").style.cursor = "pointer";
document.getElementById("computer_score").addEventListener("click", displayGuess2);
function displayGuess2(){
document.getElementById("computer_score").innerHTML = getRandomNumber2()
}
document.getElementById("computer_score").style.cursor = "pointer";
document.getElementById("you_score").addEventListener("click", displayGuess3);
function displayGuess3(){
document.getElementById("you_score").innerHTML = getRandomNumber3()
}
document.getElementById("you_score").style.cursor = "pointer";
var computerScore = document.getElementById("computer_score")
var youScore = document.getElementById("you_score")
var targetNumber = document.getElementById("target_number")
Here is my HTML. I would like to make a if else statement in script that checks if the value of target_number and computer_score are equal
<!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>Number Guesser</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<h1>Number Guesser</h1>
</div>
<div>
<h2>Round
<span class="round_number">1</span>
</h2>
</div>
<h3>Target Number: <span id="target_number">Blank</span></h3>
</body>
<div class="container">
<div class="computer">Computer
<div>Score <span id="computer_score">0</span></div>
</div>
<div class="you">You
<div>Score <span id="you_score">0</span></div>
</div>
</div>
<h1 id="new">New</h1>
<script src="script.js"></script>
</html>
Based on what it looks like you mean, I have simplified your code using event delegation, some css and a single function to generate a random number lower than 10.
const someNumberLT10 = () => Math.floor(Math.random() * 10);
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.id === "play") {
// ^ button#play was clicked
const youNr = someNumberLT10();
const computerNr = someNumberLT10();
// two random numbers < 10 are generated and stored into variables
document.querySelector(`#you_score`).textContent = youNr;
document.querySelector(`#computer_score`).textContent = computerNr;
// ^ numbers are displayed
document.querySelector(`#equal`).textContent = `Equal? ${
youNr === computerNr ? `Yes! 😊` : `Nope ... 😔`}`;
// ^ score (equal or not) is displayed
const round = document.querySelector(`[data-round]`);
round.dataset.round = +round.dataset.round + 1;
// ^ round index is set
}
}
[data-round]:after {
content:' 'attr(data-round);
}
<h2 data-round="1">Round</h2>
<!-- data-round is a so called data attribute. It can be used as a variable
in js (dataset). Here, js is used to set the value, and css is used
to display the value ([data-round]:after) -->
<h3>Target Number: <button id="play">Create</button></h3>
<div class="container">
<div>Computer score <span id="computer_score">0</span></div>
<div>Your score <span id="you_score">0</span></div>
<div id="equal"></div>
</div>
Related
I'm making a program where it has a collection of calculators, and for some reason when I try to change the innerhtml of a certain text it only changes it during the if statement and not during the else part.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
GiveAnswer.innerHTML = `Processing...`;
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
};
https://replit.com/#ButterDoesFly/Arcane-Calculators#index.html
I'm not sure but I guess the reason for this is that the function never goes to the else part because it gets break every time. Remember that .reverse() reverses the array in place so the if statement will always be true. Try to add different variable for the reversed answer.
function Palindrome() {
//Fix not changing to processing when doing new palindrome.
var Division = 0;
var input = document.getElementById("PalindromeInput").value;
var GiveAnswer = document.getElementById("PalindromeAnswer");
var Answer = String(input);
GiveAnswer.innerHTML = `Processing...`;
setTimeout(()=>{
while (0 < 1) {
if (Answer == Answer.split("").reverse().join("")) {
GiveAnswer.innerHTML = `That is a palindrome of the ${Division}th Division.`;
break
} else {
Division = Division + 1;
Answer = String(parseInt(String(Answer)) + parseInt(Answer.split("").reverse().join("")));
};
};
},1000)
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p id="PalindromeAnswer">This will tell you the number its at and then the answer.</p>
<input type="text" id="PalindromeInput" placeholder="What number would you like to enter?">
<br>
<input type="button" onclick="Palindrome()" value="Submit" id="PalindromeButton">
<script src="script.js"></script>
<!--
This script places a badge on your repl's full-browser view back to your repl's cover
page. Try various colors for the theme: dark, light, red, orange, yellow, lime, green,
teal, blue, blurple, magenta, pink!
-->
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
</body>
</html>
result is rendering very fast such that changes are not reflecting in ui..add a timeout so that changes reflect in front end
I want to create a random ruffling game where it randomly chooses the name and image of a certain user.
My problem is how would every image be linked to that specific user when it starts ruffling randomly, the image and name may not match.
I want it such that every object in the json array that has a name and an image to be matched when picking randomly
How can i do that?
here is my code:
script.js
const ENTRANTS = [{
name:"John",
image:"images/sun-rise.jpg"
},{
name:"Jack",
image:"images/tree-736885__480.jpg"
},{
name:"Jane",
image:"images/pexels-anjana-c-674010.jpg"
}];
const rollEl = document.querySelector(".roll");
const rollAgainEl = document.querySelector(".roll-again");
const namesEl = document.querySelector(".names");
const imageEl = document.querySelector(".image");
const winnerEl = document.querySelector(".winner");
const boxEl = document.querySelector(".text-box");
const winnerTextELEMENT = document.querySelector(".winnerText");
const values = Object.values(ENTRANTS)
winnerTextELEMENT.classList.add('hide')
function randomName() {
const rand = Math.floor(Math.random() * values.length);
const name = values[rand].name;
const image = values[rand].image;
namesEl.innerText = name;
imageEl.src = image
}
function rollClick() {
boxEl.classList.remove("hide")
rollEl.classList.add("hide");
rollAgainEl.classList.add("hide");
winnerEl.classList.add("hide");
namesEl.classList.remove("hide");
setDeceleratingTimeout(randomName, 10, 30);
setTimeout(() => {
namesEl.classList.add("hide");
winnerEl.classList.remove("hide");
rollAgainEl.classList.remove("hide");
const winner = namesEl.innerText;
winnerEl.innerText = winner;
winnerTextELEMENT.classList.remove('hide')
}, 4000);
}
function setDeceleratingTimeout(callback, factor, times) {
const internalCallback = ((t, counter) => {
return () => {
if (--t > 0) {
setTimeout(internalCallback, ++counter * factor);
callback();
}
};
})(times, 0);
setTimeout(internalCallback, factor);
}
index.html:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Ruffle</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<button class="roll" onclick="rollClick()">Start</button>
<span class="winnerText">WINNER</span>
<div class="text-box hide">
<img class="image" src=""/>
<div class="names hide">
</div>
<div class="winner hide"></div>
</div>
<button class="roll-again hide" onclick="rollClick()"> Start Again</button>
<script src="./script.js"></script>
</body>
</html>
Create Two Arrays using the names and images value. Use Math.Floor(Math.random * array.length)For both of the arrays to get a random value that you can use an index value for the array so you get a random index value. Then use the random number/index value to get the random name and picture you want.
You should convert the JSON into a array then do MyArray[Math.round((Math.random()*number) * 10000) / 10000] and you may get the image and name that you want selected this is all in Javascript of course
I'm trying to create an Etch-a-Sketch project, I was going well (I think) until start to create a function that apply another size to my grid element, how can I do my function setSize() reads my function showSize() value?
Explanation:
My function showSize() shows the value of a range input element, and I need to apply this value to my function populateBoard(), so I have created setSize() function to do that, Am I right creating this intermediary function to do that?
These are my codes:
function populateBoard(size){
let board = document.querySelector(".board");
board.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
board.style.gridTemplateRows = `repeat(${size}, 1fr)`;
for (let i = 0; i < 256; i++) {
let square = document.createElement("div");
square.style.backgroundColor = "green";
board.insertAdjacentElement("beforeend", square);
}
}
populateBoard(16);
function showSize(value) {
let boardSize = document.querySelector(".show-size").innerHTML = value;
}
function setSize(boardSize) {
let setSize = document.querySelector(".set");
setSize.addEventListener("click", () => {
populateBoard(boardSize);
});
}
<!DOCTYPE html>
<html>
<head>
<title>
Etch-a-Sketch
</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="container">
<div class="board">
</div>
<div class="settings">
<button class="clear">Clear</button>
<input type="range" min="8" value="16" max="128" step="8" oninput="showSize(this.value)">
<span class="show-size">16</span>
<button class="set">Set</button>
</div>
</div>
</body>
</html>
The problem is that you are defining the boardSize variable in the showSize function so that variable is only available in the scope of that function. Please read the following:
https://www.w3schools.com/js/js_scope.asp
I suggest you do the following.
document.querySelector(".set").addEventListener("click", () => {
let boardSize = document.querySelector(".show-size").innerHTML;
populateBoard(boardSize);
});
function setSize(value) {
document.querySelector(".show-size").innerHTML = value;
}
Some errors you have is setting the event listener in a function.
I would just have a function to set the board size as seen above and then the event listener to populate the board onclick of the set size button.
I am creating my program which takes the user input on an Enter key.
I use the userInput with .value in the if statement and it works perfectly. But when I try to use it as a variable, nothing is outputted and nothing is in the console.
I tried to do querySelector("input['name = "command"]') to see if it might work but again, nothing outputted and it showed nothing in the console
var userInput = document.querySelector("input[name = 'command']")
var theInput = userInput.value.toLowerCase();
var theConsole = document.querySelector("#console");
theConsole.scrollTop = 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(theInput=== "help") theConsole.append("Help is given!", p);
//using the keywords
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input type = "text" name = "command" id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
</body>
</html>
Replace the div#console element:
<div id="console">
to this input:
<input type="text" id="console">
You will want to refer to userInput.value instead of theInput. Because theInput is set to the value at the time of setting the variable and it doesn't get updated even though the value of userInput changing.
I am trying to create a very basic markdown editor. I am using a textarea on the left to type in data, and on the right, I have an entry point div where I'm storing everything I type in as I type it using a "keyup" listener. I have gotten the text to apply a class to make it bold when the code is formatted with * at the beginning and end of a word, but after the DOM is updated with this the next word I try to type in doesn't get added and is in fact showing up as blank when I run it through a debugger.
Here is the JS I have currently...
const html = document.querySelector('#html-area');
const md = document.querySelector('#markdown-area');
html.addEventListener("keyup", function(e) {
md.innerHTML = e.target.value;
const words = md.innerHTML.split(' ');
const len = words.length;
for(let i = 0; i < len; i++) {
// if the first character is * and the last character is * and the length of the current word is greater than or equal to 2 then change that word by adding the ".bold" class to it.
if(words[i][0] === "*" && words[i][words[i].length - 1] === "*" && words[i].length >= 2){
const indexOfWord = md.innerHTML.split(' ').indexOf(words[i]);
const newWord = md.innerHTML.split(' ')[indexOfWord] = ` <span class="bold">${md.innerHTML.split(' ')[indexOfWord]}</span> `;
const before = md.innerHTML.split(' ').slice(0, indexOfWord).join();
md.innerHTML = before + newWord;
break;
}
}
});
And here is my HTML...
<!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="./css/index.css" />
<title>MarkDown</title>
</head>
<body>
<!-- HTML -->
<div id="app">
<div id="html-container">
<h2>HTML</h2>
<section>
<label for="html-area"></label>
<textarea
name="html-area"
placeholder="type html here..."
id="html-area"
></textarea>
</section>
</div>
<!-- Markdown -->
<section id="markdown-container">
<h2>MarkDown</h2>
<div>
<div
id="markdown-area"
>Markdown text will show here...</div>
</div>
</section>
</div>
<script src="./index.js"></script>
</body>
</html>
Thanks for any tips or help.
One thing: here
md.innerHTML = before + newWord;
you're cutting the output with the newWord. You need to define some after similar to before, and md.innerHTML = before + newWord + after;.
Although a better solution would be to do: split - map - join. Split the input text into words, map them into either original or bold version, and join back. Something like this:
const html = document.querySelector("#html-area");
const md = document.querySelector("#markdown-area");
const bold = word =>
`<span class="bold">${word.substring(1, word.length - 1)}</span>`;
const boldOrNot = word =>
word.startsWith("*") && word.endsWith("*") && word.length > 2
? bold(word)
: word;
html.addEventListener("keyup", function(e) {
const input = e.target.value;
const output = input.split(" ").map(boldOrNot).join(" ");
md.innerHTML = output;
});
https://codepen.io/anon/pen/jRrxZx