I have the following javascript code:
let gemStones = [
"Amethyst",
"Diamond",
"Emerald",
"Ruby",
"Sapphire",
"Topaz",
"Onyx",
];
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
function findGems()
{
console.log("You found a " + randomGemStone + "!");
}
Here's the 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">
<link rel="stylesheet" href="css.css">
<title>1. Gem Pond</title>
</head>
<body>
<h1>Gem Pond</h1>
<script src="main.js"></script>
<button id="gemPond_btn" onclick="findGems()">GET GEM</button>
</body>
</html>
When I click the "GET GEM" button several times in a row, I always get the same result instead of getting a random one.
I'm not sure what I'm doing wrong here.
Thanks in advance.
Move the let randomGemStone line into the findGems function:
function findGems()
{
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
console.log("You found a " + randomGemStone + "!");
}
Otherwise you run it only once on page load and not every time you click the button.
let gemStones = [
"Amethyst",
"Diamond",
"Emerald",
"Ruby",
"Sapphire",
"Topaz",
"Onyx",
];
const findGems = () => {
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
console.log(`You found a ${randomGemStone}!`);
}
Note I have moved randomGemStone inside the function. Or the value will only be updated once when the script loads, this way it will be random everytime findGems() is called
Related
d3.interval takes two parameters, callback and delay,e.g.
d3.interval(callback, delay).
I was wondering if it is possible to pass on a dynamic delay for each interval.
For example, in the following, I am asking the interval to run at 1000ms delay. But is there a way I can ask d3.interval to run at 0ms, 1000ms, 2000ms, 3000ms respectively for interval# 1,2,3,4.
I tried like desiredDelay[counterF] but it did not work.
const masterSelection = d3.selectAll('[class^="text"]');
const node = masterSelection.nodes();
const len = node.length - 1;
let counterF = 0;
const del = 1000;
const desiredDelay = [0, 1000, 2000, 3000]
let ticker = d3.interval(
e => {
const element = masterSelection['_groups'][0][counterF];
const selection = d3.select(element).node();
console.log(selection);
counterF++;
(counterF > len) ? ticker.stop(): null
}, del
)
<!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>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<div class='text1'>one</div>
<div class='text2'>two</div>
<div class='text3'>three</div>
<div class='text4'>four</div>
</body>
<script type="text/javascript" src="prod.js"></script>
</html>
Short answer: you can't.
If you look at the source code you'll see that if the delay is not null...
if (delay == null) return t.restart(callback, delay, time), t;
...it will be coerced to a number using the unary plus operator:
t.restart = function(callback, delay, time) {
delay = +delay,
etc...
What you can do is creating your own interval function, which is out of the scope of this answer.
Adapted from this, the following works as desired and is to be used with d3.timeout.
const masterSelection = d3.selectAll('[class^="text"]');
const node = masterSelection.nodes();
const len = node.length - 1;
let counter = 0;
//const del = 1000;
const delay = [0, 1000, 2000, 3000];
function show() {
const element = masterSelection["_groups"][0][counter];
const selection = d3.select(element).node();
console.log(selection);
counter++;
if (counter > len) return
d3.timeout(show, delay[counter]);
}
show();
<!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>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<div class='text1'>one</div>
<div class='text2'>two</div>
<div class='text3'>three</div>
<div class='text4'>four</div>
</body>
<script type="text/javascript"></script>
</html>
I am creating a google extension called manga extension. It all went well until I crossed with input. I like to put an input number every time I enter a manga name in the main input, naming it with chapter with input. But when I enter a new manga name, the value of every input I entered is lost. And I don't know how to put it inside of localStorage. How should I make it?
const divInput = []
const mangaName = document.getElementById('mangaNameInList')
// the manga name
const deleteBtn = document.getElementById('deleteBtn')
let mangaChapters = document.createElement('input')
let mangaLists = document.getElementById('mangaLists')
// the div i created in html
let count = 0
mangaName.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
count += 1
mangaLists.innerHTML += `<p> ${mangaName.value}
<em>chapter</em>
<input type="number" class="mangaChapters ${count}"
onkeyup="getValue(event)">
</p>`
// the input that i was conflicted with
}
})
function getValue(event) {
if (event.key == 'Enter') {
mangaChapters = document.getElementsByClassName(`mangaChapters`)
divInput.push(mangaChapters.value)
}
}
every time I entered the main input (mangaName) and displaying it in the innerHTML, I just concatenate it with and and that's the problem, how can I get the value of every declared input that I make in inside the mangaName?
<!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="style.css">
<title>Manga Extension</title>
</head>
<body>
<h1>Manga Name Lists</h1>
<input type="text" id="mangaNameInList">
<button id="deleteBtn">DELETE ALL</button>
<div id="mangaLists"></div>
<script src="script.js"></script>
</body>
</html>
here's the html code. thanks for taking time to answer my coding question :)))
I am very new to coding and couldn't find solution with if condition for this.
I know how I can do it with html code and options, but this time I need to make it with arrays and if function.
Basically I just need a dropdown with languages (which I made) and then when I click on specific language (for example, English) - I need to change html h1 to "Hello!", when I click Latvian "Labdien" etc.
Basically I need to write a proper if function, hope you could tell me what's wrong there.
const select = document.getElementById("select"),
arr = ["Latvian", "English", "Russian"];
for (var i = 0; i < arr.length; i++) {
var option = document.createElement("OPTION"),
txt = document.createTextNode(arr[i]);
option.appendChild(txt);
option.setAttribute("value", arr[i]);
select.insertBefore(option, select.lastChild);
}
if (arr[0] = "Latvian") {
document.getElementById("heading").innerHTML = "Labdien!";
} else if (arr[1] == "English") {
document.getElementById("heading").innerHTML = "Hello!";
} else if (arr[2] == "Russian") {
document.getElementById("heading").innerHTML = "Добрый день!";
}
<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>JavaScript Dropdown</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1 class="heading" id="heading"></h1>
<select class="drop" id="select"></select>
<script src="./main.js"></script>
</body>
Still figuring out whats wrong with if statement, there is some problem in :
if(arr[0] == "Latvian")
else if(arr[1] == "English")
else if(arr[2] == "Russian").
Or maybe I need to call a function and then place it onchoice in HTML? Help.. been googling and youtubing all day
You can add a change event listener to the select element. Also, you can use the index of each language as the value of the select options, and use the same array when set the h1 inner HTML:
var select = document.getElementById("select");
var arr = [
{ id: 1, language: 'Latvian', title: 'Labdien!' },
{ id: 2, language: 'English', title: 'Hello!' },
{ id: 3, language: 'Russian', title: 'Добрый день!' }
];
for (var i = 0; i < arr.length; i++) {
var option = document.createElement("OPTION");
var txt = document.createTextNode(arr[i].language);
option.appendChild(txt);
option.setAttribute('value', arr[i].id);
select.insertBefore(option, select.lastChild);
}
// add a change event listener to handle the language title
select.addEventListener('change', changeHeading);
// trigger a change event in order to display the selected language's title
select.dispatchEvent(new Event('change'));
function changeHeading(event) {
var language = arr.find(
(language) => language.id === parseInt(event.target.value)
);
document.getElementById('heading').innerHTML = language.title;
}
<!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>JavaScript Dropdown</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1 class="heading" id="heading"></h1>
<select class="drop" id="select"></select>
<script src="./main.js"></script>
</body>
</html>
I am learning Javascript right now. I have a small issue that I can't figure out how to solve it. I would like to clear content of my html page after my function displayed "Hi hi" in web page.
<html>
<body onload="alertFunc()">
<script>
function alertFunc() {
var statement = "Hi hi"
for (let i = 0; i < statement.length; i++) {
let c = statement.charAt(i);
setTimeout(function(){
document.write(c);
},i * 1000);
}
}
</script>
</body>
</html>
try this to clear content of your site after 1 second
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning </title>
</head>
<body>
<script>
document.write('hi hi');
function alertFunc() {
setTimeout(function(){
document.write(' ');
}, 1000);
}
alertFunc();
</script>
</body>
</html>
if you want to change content with time again and again then you have to use setInterval
I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the <p> tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
</script>
<script>
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
</script>
<p id="Kilograms"><!--I want the result here--></p>
</body>
</html>
How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?
Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="Kilograms"><!--I want the result here--></p>
</body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
document.getElementById("Kilograms").innerHTML = kilog(440);
</script>
</html>
Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output
You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";
Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);