I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me
My code Random Price :
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
It took me a while to work around the recursion issues I was running into, before I came up with a better solution.
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
this.withinPercent = withinPercent || 5;
this.secondsInterval = secondsInterval || 5;
this.decimalPlaces;
if(decimalPlaces){
this.decimalPlaces = decimalPlaces;
}
var t = this, ia = [];
function rb(mn, mx){
return mx-Math.random()*(mx-mn);
}
var pn = rb(min, max);
function rn(){
var p = 1;
if(Math.floor(Math.random()*2) === 1)p = -1
return p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
}
function rf(){
var r, d = t.decimalPlaces;
pn += rn();
if(pn < min || pn > max){
return rf();
}
r = pn;
if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
return r;
}
this.setDiv = function(div){
div.innerHTML = rf(); ia = [];
var iv = setInterval(function(){
div.innerHTML = rf();
}, this.secondsInterval*1000);
ia.push(iv);
return this;
}
this.stop = function(){
for(var i=0,l=ia.length; i<l; i++){
if(ia[i]){
clearInterval(ia[i]);
}
}
ia = [];
return this;
}
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
N = function(className, inElement){
var ii = inElement || doc;
var cN = ii.getElementsByClassName(className);
if(cN){
return cN;
}
var tn = ii.getElementsByTagName('*');
for(var i=0,e,a=[],l=tn.length; i<l; i++){
e = tn[i];
if(e.className && e.className === className)a.push(e);
}
return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
fr.setDiv(fs[i]);
}
}
//]]>
/* extrnal.js */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<hr />
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
</div>
</body>
</html>
Should work now!
After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces, randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.
I think you can understand this code.
I tried to keep your code.
The key is to use setInterval function.
<!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>
<script>
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function assignData(){
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
setInterval(assignData, 5000); //every 5 seconds
}
</script>
<body onload="assignData()">
<h2 id="price1"></h2>
<h2 id="price2"></h2>
<h2 id="price3"></h2>
<h2 id="price4"></h2>
<h2 id="price5"></h2>
<h2 id="price6"></h2>
<h2 id="price7"></h2>
</body>
</html>
My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)
For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li"), but if you really want to do it using element IDs you could say .querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7").
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
}
// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
el.innerHTML = generateRandomNumber(0,99.99);
});
// update an element at random every second:
setInterval(function update() {
var element = elements[Math.floor(Math.random() * elements.length)];
var currentVal = +element.innerHTML;
element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>
Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.
Further reading:
.querySelectorAll()
Array .forEach() method
Function.prorotype.call()
Math.floor()
unary plus operator
Hope this will help.
<body>
<p id="price1"></p>
<p id="price2"></p>
<p id="price3"></p>
<p id="price4"></p>
<p id="price5"></p>
<p id="price6"></p>
<p id="price7"></p>
</body>
<script>
//set initial random number for the elements
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
//set random number to elements with fluctuation +/- 5%
setRandomToElements()
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function setRandomToElements(){
//get current prices
var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);
var fluctuation = 0.05;//5%
//random new numbers +/-5% current price
document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));
setInterval(setRandomToElements, 5000);
}
</script>
Fiddle
Related
Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!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>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>
i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`
I am trying to make a simple javascript game. I made 8 divs to present cards. I created an array. Array includes two reds, two blues, two yellow, two greens. user will click just 2 cards and if cards are same colors, user will win game. if cant find 2 same colors at once, user will lose. Now when i click a card, it gets a color from this array and i remove this color with indexOf and slice. But i want to make a code that first value and second value condition. we will get two values and ll ask if two values are same, user will win. i am adding codes and waiting your help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<div id="ana">
<div id="one" onclick="card1f()" class="firstcards"></div>
<div id="two" onclick="card2f()" class="firstcards"></div>
<div id="three" onclick="card3f()" class="firstcards"></div>
<div id="four" onclick="card4f()" class="firstcards"></div>
</div>
<div id="ana2">
<div id="five" onclick="card5f()" class="secondcards"></div>
<div id="six" onclick="card6f()"class="secondcards"></div>
<div id="seven" onclick="card7f()" class="secondcards"></div>
<div id="eight" onclick="card8f()" class="secondcards"></div>
</div>
<script>
var cards = ["red","red","yellow","yellow","blue","blue","green","green"];
function card1f() {
var card1 = document.getElementById("one").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card1);
cards.splice(index, 1);
}
function card2f() {
var card2 = document.getElementById("two").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card2);
cards.splice(index,1);
}
function card3f() {
var card3 = document.getElementById("three").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card3);
cards.splice(index, 1);
}
function card4f() {
var card4 = document.getElementById("four").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card4);
cards.splice(index, 1);
}
function card5f() {
var card5 = document.getElementById("five").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card5);
cards.splice(index, 1);
}
function card6f() {
var card6 = document.getElementById("six").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card6);
cards.splice(index, 1);
}
function card7f() {
var card7 = document.getElementById("seven").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card7);
cards.splice(index, 1);
}
function card8f() {
var card8 = document.getElementById("eight").style.backgroundColor = cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card8);
cards.splice(index, 1);
}
</script>
</html>
</body>
I did not test this, just wrote code here directly, so I'm not sure this is right.
But I think you can make your code like the concept as follow.
var col = ""
function winOrLose(color) {
if(!col) {
col = color;
return;
}
if(col == color) {
alert("You Win");
} else {
alert("You Lose");
}
cards = ["red","red","yellow","yellow","blue","blue","green","green"];
col = "";
}
And call this function in your all function like this
function card7f() {
var card7 = document.getElementById("seven").style.backgroundColor =
cards[Math.floor(Math.random() * cards.length)];
var index = cards.indexOf(card7);
winOrLose(cards[index]) // <-- call function
cards.splice(index, 1);
}
I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
<script>
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementsByClassName('boxed').innerHTML = numList;
</script>
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div class="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>
your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
};
numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div>
When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:
do {
var high = prompt('What\'s the highest number you want to generate','');
high = parseInt(high, 10);
} while (isNaN(high));
do {
var nums = prompt('How many numbers do you want to generate','');
nums = parseInt(nums, 10);
} while (isNaN(nums));
function rand(highestNum) {
var randomNumber =
Math.floor(Math.random() * highestNum) + 1;
return randomNumber;
}
var numList = [];
for (var i = 0; i < nums; i++) {
// Go through this loop quantity of times
numList.unshift(rand(high));
// add new number to end of array
console.log(numList)
};
numList.toString();
document.getElementById('boxed').innerHTML = numList;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
</head>
<body>
<div id="container">
<header>
<h1>Lucky Numbers</h1>
</header>
<main>
<div id="boxed"></div>
<p>Good luck!</p>
</main>
</div> <!-- Closing container -->
</body>
</html>
I created a simple simple javascript program where when I click two buttons that I generate random numbers and the third button allows me to sum the two numbers up and then I can reset.
Codepen with update
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button onclick="addTextNode1('Hi!');">N. 1</button>
<button onclick="addTextNode('NO! ');">N. 2</button>
<button onclick="test2('NO!.. ');">A! </button>
<button onclick="myFunction3()">Reset page</button>
<hr />
<p id="p2">1: </p>
<p id="p1">2: </p>
<p id="p3">T: </p>
</body>
</html>
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
function addTextNode1(simple2) {
text2 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text2+" "),
p2 = document.getElementById("p2");
p2.appendChild(newtext);
}
function myFunction3() {
window.location.reload(true);
}
function test2() {
text5 = text1 + text2;
var newtext5 = document.createTextNode(text5),
p3 = document.getElementById("p3");
p3.appendChild(newtext5);
}
My question is how would I be able to replace the number that was newly displayed by the button by the appendChild method, so that when I click the button again the previous number gets replaced.
Thanks! Much appreciate!
Here an example for the second number.Same for the other:
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
var p1Txt=p1.innerHTML;
var a=p1Txt.length;
if(a>=3){
p1.innerHTML='2: ';
p1.appendChild(newtext);
}else{
p1.appendChild(newtext);
}
Great to hear that you are programming!
Nice post about onclick attribute attaching events
If you need some functionality more than once,wrap this in a function.(random integer).It makes code cleaner and you dont need to repeat yourself.
Check this out.I bet this example is far from perfect but still give some insights
// You can use some library like "Lodash" to use such functions.
// returns random integer in span <min:max>
function randomInteger(min = 1, max = 100){
// in case that there are wrong values
if(min >= max){throw new Error(`Hey i cant get random integer in range min:${min} to max:${max}`)}
return Math.round((Math.random() * (max-min))+min)
}
// buttons
var number1GeneratorButton = document.getElementById('number1-generator'),
number2GeneratorButton = document.getElementById('number2-generator'),
calculateSumButton = document.getElementById('sum-button'),
resetPageButton = document.getElementById('reset-page');
// outputs
var number1Output = document.getElementById('number1'),
number2Output = document.getElementById('number2'),
sumOutput = document.getElementById('sum');
// add event listeners to the buttons
number1GeneratorButton.addEventListener('click', function(){
number1Output.innerHTML = randomInteger();
})
number2GeneratorButton.addEventListener('click', function(){
number2Output.innerHTML = randomInteger();
})
calculateSumButton.addEventListener('click', function(){
var sum = parseInt(number1Output.innerHTML) + parseInt(number2Output.innerHTML);
sumOutput.innerHTML = sum;
})
resetPageButton.addEventListener('click', reloadWindow)
function reloadWindow() {
window.location.reload(true);
}
// function addTextNode2(simple3) {
// text3 = text2 + text1
// var newtext1 = document.createTextNode(text3),
// p3 = document.getElementById("p3");
// p3.appendChild(newtext1);
// }
// function addTextNode4() {
// if (text1 > text2){
// text3 = text1 - text2;
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3");}
// else if(text2 > text1){
// text3 = text2 - text1;");}
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3
// p3.appendChild(newtext4);
// }
// function test(sampleplace1){
// if(text1 > text2){
// q = text1 - text2;
// var storm = document.createTextNode(q).value,
// p1 = document.getElementById("p1");}
// else if(text2 > text1){
// z = text2 - text1;
// var storm = document.createTextNode(z).value,
// p1 = document.getElementById("p1");
// }
// p1.appendChild(storm);
// }
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button id="number1-generator">Number1Generator</button>
<button id="number2-generator">Number2Generator</button>
<button id="sum-button">CalculateSum</button>
<button id="reset-page">Reset page</button>
<hr />
<p>Number1: <span class="numbers" id="number1"></span></p>
<p>Number2: <span class="numbers" id="number2"></span></p>
<p>Sum: <span id="sum"></span></p>
</body>
</html>