This piece of javascript successfully generated random number but I'm having challenge in fetching the variable value so I can use it as desired. below is the working code:
let btn = document.querySelector('button');
let output = document.querySelector('#output');
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() * step1;
let result = Math.floor(step2) + min;
return result;
}
function createArrayOfNumbers(start, end){
let myArray = [];
for(let i = start; i <= end; i++) {
myArray.push(i);
}
return myArray;
}
let numbersArray = createArrayOfNumbers(1,10);
btn.addEventListener('click', () => {
if(numbersArray.length == 0){
output.innerText = 'No More Random Numbers';
return;
}
let randomIndex = getRandomNumber(0, numbersArray.length-1);
let randomNumber = numbersArray[randomIndex];
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
});
<!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>
<button>Generate</button>
<h1 id="output" style="text-align: center">Random Number</h1>
<script src="script.js"></script>
</body>
</html>
There are several ways of doing but the easiest would be to create a global variable outside the function and then when that random number is generated assign that number to that global variable you can write it like this:
var myvariable = 0;
let btn = document.querySelector('button');
let output = document.querySelector('#output');
//all of your code and then at the end
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
myvariable = randomNumber;
});
Now this variable is accessible outside the function. Hope that helps!
So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};
I am very new to Javascript and am writing a little webapp that, among other things, generates random strings (used for visualisation, doesn't need to be perfectly random).
The site consists of three divs, which each should generate a random string. On pageload, the divs display 20 hyphens as visual placeholders. Within each div I then want to replace one hyphen after the other with a random character, waiting 100ms between each iteration.
I got this working just fine with one div. But as soon as I do this with multiple divs, each randomly generated character gets immediately overwritten by the almost simultaneously randomly generated character in the following div.
I also added a console.log, so you can see that initially, each div generates a random character, but then the third div overwrites the character in the two other divs.
I'm assuming this is something I'm just not getting yet, so my question:
How can I keep this from happening, so that each div keeps its own string (and why is this happening in the first place)?
Thanks for your help, let me know if you need anything else!
const placeholderLength = 20;
let valueForm = [],
valueModus = [],
valueInhalt = [],
placeholder = [];
let valueJoined;
const outputForm = document.getElementById("outputForm");
const outputModus = document.getElementById("outputModus");
const outputInhalt = document.getElementById("outputInhalt");
const randomCharacter = () => {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
return characters.charAt(Math.floor(Math.random() * characters.length));
};
const initialValues = (value, destination, identifier) => {
let i = 0;
const loop = () => {
setTimeout(() => {
value[i] = randomCharacter();
valueJoined = value.join("");
destination.innerHTML = valueJoined;
i++;
if (i < placeholderLength) {
loop();
}
console.log(identifier, valueJoined);
}, 100);
};
loop();
};
const main = () => {
for (let i = 0; i < placeholderLength; i++) {
placeholder.push("-");
}
valueForm = valueModus = valueInhalt = placeholder;
initialValues(valueForm, outputForm, "value 1");
initialValues(valueModus, outputModus, "value 2");
initialValues(valueInhalt, outputInhalt, "value 3");
};
main();
.output {
font-family: monospace;
letter-spacing: 1px;
}
<!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" />
<link rel="stylesheet" href="main.css" />
<title>Document</title>
</head>
<body>
<h1>Random Values</h1>
<h2>Value 1</h2>
<div id="outputForm" class="output"></div>
<h2>Value 2</h2>
<div id="outputModus" class="output"></div>
<h2>Value 3</h2>
<div id="outputInhalt" class="output"></div>
</body>
<script src="app.js"></script>
</html>
The problem is that you assign the same placeholder array to all three generators. Since arrays are objects and objects are passed (and assigned) by reference, after this line:
valueForm = valueModus = valueInhalt = placeholder
...they will point to the same array object. Mutating that object will change it for each generator.
To solve the issue, remove that line:
const placeholderLength = 20;
let valueForm = [],
valueModus = [],
valueInhalt = [],
placeholder = [];
let valueJoined;
const outputForm = document.getElementById("outputForm");
const outputModus = document.getElementById("outputModus");
const outputInhalt = document.getElementById("outputInhalt");
const randomCharacter = () => {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
return characters.charAt(Math.floor(Math.random() * characters.length));
};
const initialValues = (value, destination, identifier) => {
let i = 0;
const loop = () => {
setTimeout(() => {
value[i] = randomCharacter();
valueJoined = value.join("");
destination.innerHTML = valueJoined;
i++;
if (i < placeholderLength) {
loop();
}
console.log(identifier, valueJoined);
}, 100);
};
loop();
};
const main = () => {
for (let i = 0; i < placeholderLength; i++) {
placeholder.push("-");
}
//valueForm = valueModus = valueInhalt = placeholder;
initialValues(valueForm, outputForm, "value 1");
initialValues(valueModus, outputModus, "value 2");
initialValues(valueInhalt, outputInhalt, "value 3");
};
main();
.output {
font-family: monospace;
letter-spacing: 1px;
}
<!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" />
<link rel="stylesheet" href="main.css" />
<title>Document</title>
</head>
<body>
<h1>Random Values</h1>
<h2>Value 1</h2>
<div id="outputForm" class="output"></div>
<h2>Value 2</h2>
<div id="outputModus" class="output"></div>
<h2>Value 3</h2>
<div id="outputInhalt" class="output"></div>
</body>
<script src="app.js"></script>
</html>
To assign hyphens to the arrays, you can clone the array (e.g. by using Array#slice()):
const placeholderLength = 20;
let valueForm = [],
valueModus = [],
valueInhalt = [],
placeholder = [];
let valueJoined;
const outputForm = document.getElementById("outputForm");
const outputModus = document.getElementById("outputModus");
const outputInhalt = document.getElementById("outputInhalt");
const randomCharacter = () => {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
return characters.charAt(Math.floor(Math.random() * characters.length));
};
const initialValues = (value, destination, identifier) => {
let i = 0;
const loop = () => {
setTimeout(() => {
value[i] = randomCharacter();
valueJoined = value.join("");
destination.innerHTML = valueJoined;
i++;
if (i < placeholderLength) {
loop();
}
console.log(identifier, valueJoined);
}, 100);
};
loop();
};
const main = () => {
for (let i = 0; i < placeholderLength; i++) {
placeholder.push("-");
}
valueForm = placeholder.slice();
valueModus = placeholder.slice();
valueInhalt = placeholder.slice();
initialValues(valueForm, outputForm, "value 1");
initialValues(valueModus, outputModus, "value 2");
initialValues(valueInhalt, outputInhalt, "value 3");
};
main();
.output {
font-family: monospace;
letter-spacing: 1px;
}
<!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" />
<link rel="stylesheet" href="main.css" />
<title>Document</title>
</head>
<body>
<h1>Random Values</h1>
<h2>Value 1</h2>
<div id="outputForm" class="output"></div>
<h2>Value 2</h2>
<div id="outputModus" class="output"></div>
<h2>Value 3</h2>
<div id="outputInhalt" class="output"></div>
</body>
<script src="app.js"></script>
</html>
You can also move the slicing part to the initialvalues function, you don't have to repeat yourself:
const placeholderLength = 20;
let valueForm,
valueModus,
valueInhalt,
placeholder = [];
let valueJoined;
const outputForm = document.getElementById("outputForm");
const outputModus = document.getElementById("outputModus");
const outputInhalt = document.getElementById("outputInhalt");
const randomCharacter = () => {
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
return characters.charAt(Math.floor(Math.random() * characters.length));
};
const initialValues = (originalValue, destination, identifier) => {
let i = 0;
const value = originalValue.slice()
const loop = () => {
setTimeout(() => {
value[i] = randomCharacter();
valueJoined = value.join("");
destination.innerHTML = valueJoined;
i++;
if (i < placeholderLength) {
loop();
}
console.log(identifier, valueJoined);
}, 100);
};
loop();
};
const main = () => {
for (let i = 0; i < placeholderLength; i++) {
placeholder.push("-");
}
valueForm = valueModus = valueInhalt = placeholder;
initialValues(valueForm, outputForm, "value 1");
initialValues(valueModus, outputModus, "value 2");
initialValues(valueInhalt, outputInhalt, "value 3");
};
main();
.output {
font-family: monospace;
letter-spacing: 1px;
}
<!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" />
<link rel="stylesheet" href="main.css" />
<title>Document</title>
</head>
<body>
<h1>Random Values</h1>
<h2>Value 1</h2>
<div id="outputForm" class="output"></div>
<h2>Value 2</h2>
<div id="outputModus" class="output"></div>
<h2>Value 3</h2>
<div id="outputInhalt" class="output"></div>
</body>
<script src="app.js"></script>
</html>
Fairly new to Javascript here. I have a to do list, and I am in the process of adding a feature to Hide all checked items (which have a class .checked).
The idea i have, is to add a display property to the class(that all checked items receive) but how do I do it? Is there any other way for me to be able to add a display property to all of the checked items?
Here's the code (didn't include the other css as it was unnecesary):
//ADD NEW ELEMENT SECTION
function newElement() {
var inputval = document.getElementById('inputnewlist').value;
var li = document.createElement('li');
var lichild = document.createTextNode(inputval);
li.appendChild(lichild);
if (inputval === '') {
alert('you must put something in the textbox!');
} else {
document.getElementById('mylist').appendChild(li);
}
document.getElementById('inputnewlist').value = "";
//REMOVE BUTTON SECTION
var button = document.createElement('button');
var buttonval = document.createTextNode('x');
button.classList.add("exit");
button.appendChild(buttonval);
li.appendChild(button);
var exit = document.querySelectorAll('.exit');
for (b = 0; b < exit.length; b++) {
exit[b].addEventListener('click', removeButtonParent);
}
}//end of create newelement function
var exit = document.querySelectorAll('.exit');
for (z = 0; z < exit.length; z++) {
exit.addEventListener('click', removeButtonParent);
}
function removeButtonParent() {
event.target.parentElement.remove();
}
//ENTER KEY PRESS-BUTTON PRESS
function enterfunction(event) {
var key = document.getElementById('inputnewlist');
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById('addbutton').click();
}}
//CHECK BUTTON SECTION
var list = document.querySelector('ul');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') {
event.target.classList.toggle('checked');
}
}, false);
//HIDE CHECKED LIST ITEMS
function hideCheck() {
if (event.target.checked === true) {
var checkLI = document.querySelectorAll('.checked');
checkLI.style.display = "none";
}
else {
var checkliELSE = document.querySelectorAll('.checked');
checkLI.style.display = "";
}
}
.checked {
background-color: darkgrey;
text-decoration: line-through;
}
<!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">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div id="formcontainer">
<h1 class="title"> To Do List </h1>
<input type="text" name="inputnewlist" id="inputnewlist" placeholder="Add thing to do.." onkeydown="enterfunction(event)">
<button onclick="newElement()" class="addbutton" id="addbutton">Add</button>
</div>
<ul id="mylist">
</ul>
<input type="checkbox" id="hidecheck" onchange="hideCheck()"> <label for="hidecheck"> Hide the checked list items</label>
<script src="scripts.js"></script>
</body>
You can try the following code by adding the style 1 by 1.
function hideCheck() {
if (event.target.checked === true) {
var checkLIs = document.querySelectorAll('.checked');
for (let i = 0; i < checkLIs.length; i++){
checkLIs[i].style.display = "none";
}
}
}
I looked at a few examples on how to make a typewriter effect but my solution doesn't seem to work.I have three sentences that I want to loop forever and have them typed letter by letter to get that typewriter effect. Here is my code:
<html>
<head>
<meta charset="utf-8">
<title>Кухнята на Дани</title>
<link rel="stylesheet" href="css.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script> <!--required for the next script-->
<!--some other javascript that requires the JQuery code above-->
<script type="text/javascript">
function typeWriter(){
var flag=0;
while(flag=0)
{
var s1 = "sentence1";
var s2 = "sentence2";
var s3 = "sentence3";
var s = "";
var i = 0;
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s1.length; i++)
{
s=s1.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s2.length;i++)
{
s=s2.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
document.getElementById("sub-element").innerHTML=s;
for(i=0; i<s3.length;i++)
{
s=s3.charAt(i);
document.getElementById("sub-element").innerHTML = document.getElementById("sub-element").innerHTML+s;
setTimeout(typeWriter, 50);
}
s="";
}
}
</script>
</head>
<body onload = "typeWriter()">
<header>
<!--header and navigation stuff here-->
</header>
<section id="home">
<div class="container">
<h1>Кухнята на Дани</h1>
<p id="sub-element"></p> <!--the text will appear in this paragraph-->
</div>
</section>
</body>
</html>
Due to some reason, the Javascript code won't work.
Excuse me for my code. I know it's too long but I decided to include everything that might be important.
You are using a while loop, meaning that even though you are appending one letter at a time it happens too fast (and in the same render frame) and thus you dont see the type effect.
You need to execute the function on some time interval, for example
setInterval(appendLetter, 200)
Which will execute appendLetter function every 200 ms and there you can have your chars append logic.
const text = "some text to loop"
let charIndex = 0;
function appendLetter() {
document.getElementById("aaa").innerHTML = text.substr(0, charIndex)
charIndex++;
if(charIndex > text.length) charIndex = 0;
}
setInterval(appendLetter, 250);
Try this
<section id="home">
<div class="container">
<h1>Кухнята на Дани</h1>
<p id="newmsg"></p> <!--the text will appear in this paragraph-->
</div>
</section>
Javascript code
var im = 0, ij=0;
var txtarray = ['sentence1', 'sentence2', 'sentence3'];
var speed = 100;
function typeWriter() {
if (im < txtarray[ij].length) {
document.getElementById("newmsg").innerHTML += txtarray[ij].charAt(im);
im++;
setTimeout(typeWriter, speed);
}
else{
setTimeout(repeatt, 1000);
}
}
typeWriter();
function repeatt() {
document.getElementById("newmsg").innerHTML = "";
im=0;
if(ij < txtarray.length-1){
ij++;
}
else{
ij = 0;
}
typeWriter();
}