How to change the loop to reverse the square print in Javascript - javascript

I'm learning java script and I'm currently working with testing in javiscritp, I've done this code that you can look at, but I don't know how to reverse now the order of these cubes to be 2 up and 1 down (see what I want in the picture) I know I need to change something for loops but I fail in any way to get what I want.
let Tabela = (function () {
const dajRed = function (tabela) {
let red = document.createElement("tr");
tabela.appendChild(red);
return red;
}
const dajCeliju = function (red, prikazi) {
let celija = document.createElement("td");
if (!prikazi) celija.style = "display:none;";
red.appendChild(celija)
return celija;
}
const crtaj = function (x, y) {
const body = document.getElementsByTagName("body")[0];
let tabelaEl = document.createElement("table");
body.appendChild(tabelaEl);
for (let i = 0; i < y; i++) {
let red = dajRed(tabelaEl);
for (let j = 0; j < x; j++) {
dajCeliju(red, j < i);
}
}
}
return {
crtaj: crtaj
}
}());
//table.crtaj(3,3)
//i=0 ⍉⍉⍉
//i=1 ⎕⍉⍉
//i=2 ⎕⎕⍉
//Tabela.crtaj(8, 8);
let assert = chai.assert;
describe('Tabela', function() {
describe('crtaj()', function() {
it('should draw 3 rows when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
assert.equal(redovi.length, 3,"Broj redova treba biti 3");
});
it('should draw 2 columns in row 2 when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
let kolone = redovi[2].getElementsByTagName("td");
let brojPrikazanih = 0;
for(let i=0;i<kolone.length;i++){
let stil = window.getComputedStyle(kolone[i])
if(stil.display!=='none') brojPrikazanih++;
}
assert.equal(brojPrikazanih, 2,"Broj kolona treba biti 2");
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<style>
td{
border: 1px solid black;
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<div id="ispis"></div>
<div id="mocha"></div>
<script src="https://unpkg.com/chai/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script src="tabela.js"></script>
<script src="test.js"></script>
<script class="mocha-exec">
mocha.run();
</script>
</body>
</html>

Invert the check in dajCeliju:
if (prikazi) celija.style = "display:none;";
OR second option - change the params:
dajCeliju(red, j >= i);
Is this what you need?

Related

Function creates unwanted copy of an array as an element of itself

Basically, I have a function that creates N input fields based on user choice, then I want to get those inputs for processing later on, though for some reason it creates a copy of the return over and over again, unless I add something like "conj.pop()" in the return. I wouldn't like to work not knowing why it only works if I pop the last one.
I put a console.log to keep track and the returned array was something like this:
Array(3)
0: 'A'
1: 'B'
2: (3) ['A','B','Array(3)]
If you expand this last array it repeats infinitely this very same description.
OBS: The inputs I've been using were simple 2,2 and A B, C D.
OBS2: The code wasn't previously in english so I translated some stuff, and left other small ones as they were variables only.
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", (tipo + i));
parent.appendChild(input);
if (qtd > 5) {
if (((i + 1) % 3) == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
}
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
}
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
conjE.push(inputFields("esp", conjE));
conjC.push(inputFields("car", conjC));
console.log(conjE);
console.log(conjC);
}
}
* {
font-family: 'Roboto', sans-serif;
font-size: 14pt;
margin-top: 1rem;
}
.invisivel {
display: none;
}
label {
margin-top: 1rem;
}
input {
margin-top: 0.5rem;
margin-right: 1rem;
margin-bottom: 0.5rem;
}
button {
margin-top: 1rem;
}
<!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>DOC</title>
<link rel="stylesheet" href="style.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=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- PART 1 -->
<div id="parte1">
<form>
<label>N1</label><br>
<input type="text" id="esp_qtd"><br>
<label>N2</label><br>
<input type="text" id="car_qtd"><br>
<button id="ok1" type="button">OK</button>
</form>
</div>
<!-- PART 2 -->
<div id="parte2" class="invisivel">
<div id="esp_lista">
<label>ELEMENTS 1</label><br>
</div>
<div id="car_lista">
<label>ELEMENTS 2</label><br>
</div>
<button id="ok2" type="button">OK</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Please change your JS as follows:
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", tipo + i);
parent.appendChild(input);
if (qtd > 5) {
if ((i + 1) % 3 == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
};
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
console.log("Conj:" + qtd);
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
};
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
inputFields("esp", conjE);
inputFields("car", conjC);
console.log(conjE);
console.log(conjC);
};
};
I have only removed conjE.push() and conjC.push().
Explanation:
You are passing an array to store your data in it. But you're also returning the same array and storing it in it again. This creates an infinite loop of values. Either pass the variable or return the list.

how to delete card and index of array when a remove button clicked?

Hello I want to delete the whole card and the data in index of array when the remove button clicked.
I show it to you in this photo.
here is my code :
var list;
function setData() {
for (var i = 0; i < list.length; i++) {
var card = document.createElement("li");
var img = document.createElement("img");
var cardBody = document.createElement("div");
var cardTitle = document.createElement("h4");
var cardText = document.createElement("p");
var submit = document.createElement("a");
var remove = document.createElement("a");
card.className = "card col-md-3 col-sm-4";
cardBody.className = "card-body";
img.className = "card-img-top";
cardTitle.className = "card-title";
cardText.className = "card-text";
submit.className = "btn btn-primary stretched-link";
remove.className = "btn btn-danger stretched-link";
img.src = list[i].avatar;
cardTitle.append(document.createTextNode(list[i].first_name + list[i].last_name));
cardText.append(document.createTextNode(list[i].email));
submit.append(document.createTextNode("submit"));
remove.append(document.createTextNode("remove"));
cardBody.appendChild(cardTitle);
cardBody.appendChild(cardText);
cardBody.appendChild(submit);
cardBody.appendChild(remove);
card.appendChild(img);
card.appendChild(cardBody);
$("#list").append(card);
}
}
$(document).ready(function () {
$.ajax({
url: "https://reqres.in/api/users",
type: "get",
contentType: "application/json",
headers: {
"Access-Control-Allow-Origin": "*",
},
success: function (data) {
list = data.data;
console.log(list);
setData();
},
error: function (request, status, errorThrown) {
console.log("error", +status + errorThrown);
},
});
});
.card {
width: 100%;
margin-bottom: 5px;
}
img {
width: 100%;
}
a {
margin: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>GETTING STARTED WITH BRACKETS</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<ul class="row" id="list">
</ul>
</body>
</html>
I want to remove the index of the date in list when user clicked in the remove button on that index and then call setdate();
thanks a lot I am new in web development.
You require a click event for your delete button:
remove.addEventListener('click', function(ev) {
var btn = ev.target
var cardBody = btn.parentElement
var card = cardBody.parentElement
card.parentElement.removeChild(card)
setData()
})
Or with ES6 arrow functions () => {}, which preserves the scope where the function was created in:
remove.addEventListener('click', (ev) => {
card // from your creating function
card.parentElement.removeChild(card)
setData()
})
just before $("#list").append(card) add a click event to the card like this :
card.addEventListener('click',(event)=>{
if(event.terget.innerText === 'remove'){
card.remove()
}
})
Assuming that your list variable is a global variable, If you want to resue the setData function. Please
do it in the below way,
add the remove function for removing data in list.
function removeData(index) {
// index starts from 0
let tempList = [];
for (var i = 0; i < list.length; i++) {
if (i != index)
tempList.push(list[index]);
}
list = tempList;
setData();}
Now,
function setData() {
$("#list").empty();
// add eventlistener to remove tag to call the removeDataFunction, rest all code remains the same
for (var i = 0; i < list.length; i++) {
var card = document.createElement("li");
var img = document.createElement("img");
.
.
.
.
.
remove.addEventListener('click', removeData(i))
$("#list").append(card);
}}}

Button for each item in localstorage

How to add button for each item in localstorage to remove that item?
I have code for setItem and getItem from localstorage, but I don't know how I can add a button or x for each item to remove it.
2020-03-01 March x
2020-04-01 April x
It looks like add item to card or remove item from card.
plz help me
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#inpkey").datepicker();
});
</script>
<style>
fieldset{
margin-bottom:20px;
}
input{
padding: 7px;
height:40px;
}
</style>
</head>
<body>
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
<script>
const inpkey = document.getElementById("inpkey");
const inpavv = document.getElementById("inpvalue");
const spara = document.getElementById("btninsert");
const output = document.getElementById("output");
spara.onclick = function () {
const key = inpkey.value;
const value = inpavv.value;
console.log(key);
console.log(value);
if (key && value ) {
localStorage.setItem(key, value );
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(localStorage.getItem(key));
output.innerHTML += `${key}:&nbsp&nbsp&nbsp&nbsp ${value} <p />`;
}
</script>
</body>
</html>
Something like this: Note JSFiddle had trouble removing the last element. Might be something I overlooked in the code. Good luck.
const setup = () => {
const spara = document.querySelector('#btninsert');
const output = document.querySelector('#output');
spara.addEventListener('click', addMyEntry);
output.addEventListener('click', removeMyEntry);
insertEntries(output);
};
const insertEntries = (target) => target.insertAdjacentHTML('beforeend', loadEntryHTML());
const loadEntryHTML = () => {
let html = '';
if(localStorage.length !== 0) {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
html += createEntryHTML(key, value);
}
}
return html;
};
const createEntryHTML = (key, value) => `<p><label class="lbl_key">${key}:</label><span class="sp_value">${value}</span> remove<p/>`;
const addMyEntry = () => {
const inpkey = document.querySelector('#inpkey');
const inpavv = document.querySelector('#inpvalue');
const key = inpkey.value;
const value = inpavv.value;
if (key && value ) {
localStorage.setItem(key, value );
const output = document.querySelector('#output');
output.insertAdjacentHTML('beforeend', createEntryHTML(key, value));
}
};
const removeMyEntry = (event) => {
const target = event.target;
if(target.nodeName === 'A') {
event.currentTarget.removeChild(target.parentNode);
localStorage.removeItem(target.dataset.key);
}
};
//load
window.addEventListener('load', setup);
.lbl_key {
padding-right: 1em;
}
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
A better solution to build elements dynamically.
const app = document.getElementById("app");
const localStorage = [1, 2, 3, 4];
for (let index = 0; index < localStorage.length; index++) {
// const key = localStorage.key(index);
// const value = localStorage.getItem(key);
let div = document.createElement("div");
div.className = "cart_item";
div.id = "cart_item_" + index;
div.textContent = localStorage[index] + new Date().toUTCString() + "";
let cross = document.createElement("span");
cross.className = "cross";
cross.textContent = " X";
cross.addEventListener("click", function remove() {
alert("Remove item");
});
div.appendChild(cross);
app.appendChild(div);
}
<!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>Static Template</title>
<link rel="stylesheet" href="app.css" />
<!-- <script src="https://deepak-proxy-server.herokuapp.com/https://gist.githubusercontent.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781/raw/e7377474ce9e411b4d8de4b10f4437a24774c0e2/Mapper.js"></script> -->
<style>
.cart_item{
border: 1px solid;
padding: 20px 40px;
}
.cross {
color: red;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
</div>
</body>
</html>

how i can insert elements in the div from javascript?

This is my html here i am taking elements from user and trying to update in js.
This my script file
// Initializing the Stack Class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push; // Inserting the element in Stack
this.pop = pop; //Removing the element in Stack
this.peek = peek;
this.clear = clear;
this.length = length;
}
// Adding an element in Stack
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top - 1];
}
// Removing an element from the given stack
function pop() {
return this.dataStore[-this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
function pushToStack(el){
s.push(el);
}
<!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> <!-- <div> <input type="text" id="stackName"> <button onclick="MakeStack()">Make a stack</button> </div> -->
<div>
<input type="text" id="elemet">
<button onclick="pushToStack(document.getElementById('elemet').value)">
Push an elemet
</button>
</div>
<div class="container"></div>
<script src="script.js"></script>
</body>
</html>
What i want is that when i click on push button the data from text filed should save in array as stack and data should show in container as my element of Stack. Thanks for help.
append the input to the Container, here is the code. Hope this is what you are looking for.
// Initializing the Stack Class
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push; // Inserting the element in Stack
this.pop = pop; //Removing the element in Stack
this.peek = peek;
this.clear = clear;
this.length = length;
}
// Adding an element in Stack
function push(element) {
this.dataStore[this.top++] = element;
}
function peek() {
return this.dataStore[this.top - 1];
}
// Removing an element from the given stack
function pop() {
return this.dataStore[-this.top];
}
function clear() {
this.top = 0;
}
function length() {
return this.top;
}
var s = new Stack();
function pushContainer(el){
//console.log(el);
var x = document.getElementById("container");
x.appendChild(el);
}
function pushToStack(el){
//
var newElement = document.createElement("p");
var Textnode = document.createTextNode(el);
newElement.appendChild(Textnode);
pushContainer(newElement);
s.push(el);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div>
<input type="text" id="elemet">
<button onclick="pushToStack(document.getElementById('elemet').value)">Push an elemet</button>
</div>
<div id="container">
</div>
</body>
</html>
You can modify your push function as :
function pushToStack(el){
s.push(el);
var para = document.createElement("p");
var node = document.createTextNode(el);
para.appendChild(node);
document.querySelector('.container').appendChild(para);
}
for working code, please refer:this pen
Modify your push function then:
function push(element) {
this.dataStore[this.top++] = element;
var div = document.createElement('div');
div.textContent = element;
document.getElementById('container').appendChild(div);
}

Javascript SetInterval and get value Math.random

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

Categories