how to make list with for loop? - javascript

I tried to made a list with a for Loop and now I'm stuck because the program isn't showing any error but is not building any list elements. Can somebody explain why and how?
It seems that it can read the value of the input element which I thought don`t seems to be the problem, so I was thinking that it must be the problem with reading it from the array. But I am just a beginner so when someone knows the actual solution to the problem, I would appreciate it.
let array = [];
function buildList() {
let ul = document.getElementById("prototype_List");
ul.innerHTML = "";
for (i = 0; i < array.length; i++) {
let list = document.createElement("li");
list.innerText = array[i];
let setting = document.getElementById("prototype_List");
setting.append(list);
}
}
function Name_Tag() {
let checkName = document.getElementById("textfeld").value;
if(checkName.length === 0) {
alert("write Name");
} else {
array.push(checkName);
buildList();
}
}
<!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">
<script src="test.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="input-group mb-3">
<button onclick="Name_Tag" class="btn btn-outline-secondary" type="button" id="button-addon1">ADD Name</button>
<input id="textfeld" type="text" class="form-control" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>
<ul id="prototype_List">
</ul>
</div>
</body>
</html>

Related

loop over elements in div

New to javascript so please be kind.
I am trying to loop over a all the elements in the "wrapper" class to show each element for x amount of time. This code just shows all elements at once.
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="./style.css">
<title>Cell One</title>
</head>
<body>
<div class="wrapper">
<div class="x" id="inner">
<p>Test</p>
</div>
<div class="x" id="inner">
<p>Testing</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
Javascript
var divOne = document.getElementsByClassName('x')
console.log(divOne.length)
for (let i=0, len = divOne.length; i < len; i++) {
setTimeout(() => {
divOne[i].style.display = 'none';
}, 5000)
}
The reason is due to below code
setTimeout(() => {
divOne[i].style.display = 'none';
}, 5000)
Which will make all the element hide after 5000 millseconds,so you need to set them sepeartely
var divOne = document.getElementsByClassName('x')
for (let i=0, len = divOne.length; i < len; i++) {
setTimeout(() => {
for(let j=0;j<len;j++){
if(j==i){
divOne[j].style.display = 'inline-block';
}else{
divOne[j].style.display = 'none';
}
}
}, 5000*i)
}
.x{
display:none;
}
<!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>Cell One</title>
</head>
<body>
<div class="wrapper">
<div class="x" id="inner">
<p>Test</p>
</div>
<div class="x" id="inner">
<p>Testing</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
The setTimeout waits the 5000ms specified. The reason to hide all elements at the same time is that this code have created all Timeouts with same executing time, making all Timeouts runs at the same time.
The solution is when create the Timeout, pass the ms duration major of the previous, can be done like this:
for (let i=0, len = divOne.length; i < len; i++) {
setTimeout(() => {
divOne[i].style.display = 'none';
}, 5000 * (i+1))
}
Look at the second parameter of setTimeout, we add the 5000ms multiplicated by index of loop + 1 (because the var i starts with 0).
Try code:
var divOne = document.getElementsByClassName('x')
console.log(divOne.length)
for (let i=0, len = divOne.length; i < len; i++) {
setTimeout(() => {
divOne[i].style.display = 'none';
}, 5000 * (i+1))
}
<!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>Cell One</title>
</head>
<body>
<div class="wrapper">
<div class="x" id="inner">
<p>Test</p>
</div>
<div class="x" id="inner">
<p>Testing</p>
</div>
</div>
</body>
</html>
To loop over a all the elements in the "wrapper" class to show each element for x amount of time
Lets try this code
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="./style.css">
<title>Cell One</title>
</head>
<body>
<div class="wrapper">
<div class="x" id="inner">
<p>Test</p>
</div>
<div class="x" id="inner">
<p>Testing</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
here is a JavaScript code which will iterate loop over class name x and hide them with x amount of time one by one
Javascript
let x = document.querySelectorAll('.x')
for (let i=0; i < x.length; i++)
{
setTimeout(() => {x[i].style.display = 'none';},5000*i+1)
}

Pushing values into an array

When a value(person) is entered, the code create a <li> with the name of it. Multiple names, multiple <li>. I would also like to push all the values into people for future use.
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
let people
const generateTemplate = todo => {
const html = `
<li>
<span>${todo}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
}
addForm.addEventListener('submit', e => {
const todo = addForm.add.value.trim();
e.preventDefault();
if (todo.length) {
if (people === null) {
people = [];
}
people.push(todo);
console.log(people)
}
generateTemplate(todo);
addForm.reset();
people.push(todo)
console.log(people)
});
<!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="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>Group generator</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
<input type="submit" value="submit them">
<p>you can also press enter instead</p>
</form>
<ul class="todos">
</ul>
</body>
</html>
Instead of people===null use if (!people), because people is undefined at first time:
if (!people) {
people = [];
}
<!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="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>Group generator</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
<input type="submit" value="submit them"> <p>you can also press enter instead</p>
</form>
<ul class="todos">
</ul>
<script>
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
let people
const generateTemplate = todo => {
const html = `
<li>
<span>${todo}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
}
addForm.addEventListener('submit', e => {
debugger
const todo = addForm.add.value.trim();
e.preventDefault();
if (todo.length) {
if (!people) {
people = [];
}
people.push(todo);
console.log(people)
}
generateTemplate(todo);
addForm.reset();
people.push(todo)
console.log(people)
});
</script>
</body>
</html>

Local Storage on a to do list

This is a typical todo list. Items can be added or removed,it works like this but unfortunately when I refresh it disappears. I wanted to use the localStorage functionality to solve the issue. I managed to create an array where to store the items. Now I want to show in the browser the items stored in tasks. I've got stuck when I load document.addEventListener('DOMContentLoaded', getTasks) and in particular getTasks(). I have set console.log('bonjour'), to test it and it does not go through.
Thank you, as always
function getTasks() {
console.log('bonjour')
let tasks;
if(localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.forEach(task => {
const html = `
<li>
<span>${task}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
console.log('hi')
});
}
<!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="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>To do list</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
</form>
<ul class="todos">
<li>
<span>marco</span>
<i class="far fa-trash-alt delete"></i>
</li>
</ul>
<script src="app.js"></script>
</body>
</html>
function getTasks() {
console.log('bonjour')
let tasks
if (localStorage.getItem('tasks') === null) {
tasks = []
} else {
tasks = JSON.parse(localStorage.getItem('tasks'))
}
let list = document.getElementById('theList')
tasks ? .forEach((task) => {
const html = `
<li>
<span>${task}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html
console.log('hiiiii')
})
}
function storeValue(val) {
if (!val) return
if (!localStorage.getItem('tasks')) {
let tasks = []
tasks.push(val)
localStorage.setItem('tasks', JSON.stringify(tasks))
getTasks()
} else {
let tasks = JSON.parse(localStorage.getItem('tasks'))
tasks.push(val)
localStorage.setItem('tasks', JSON.stringify(tasks))
getTasks()
}
}
getTasks()
<!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="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<!-- <form action="" class="add"> -->
<h1>To do list</h1>
<input type="text" id="name" name="add" placeholder="Enter name here" onchange="storeValue(this.value)">
<!-- </form> -->
<ul class="todos" id="theList">
<li>
<span>marco</span>
<i class="far fa-trash-alt delete"></i>
</li>
</ul>
<script src="app.js"></script>
</body>
</html>
here is the solution try it on your local system here you will get an error so it is better to test on your own system. Also clean up the code I just resolved the issue

JS Function doubles

I should find the factorial of a number written in input. I have the function but the problem is that how many time I press on button it will *2 the number. I am not able to empty the value of the input and .
Here is the code.
Thank you in advance!
let sum = 1;
function faktorial(){
let faktorial1 = +inp1.value
for(let i = 1; i < faktorial1; i++){
sum *=i+1
}
tpel.innerHTML = sum
}
<!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>
<input type="text" name="" id="inp1">
<!-- <input type="text" name="" id="inp2"> -->
<br>
<!-- <button onclick="show()">Print</button> -->
<button onclick="faktorial()">Faktorial</button>
<h1 id="tpel"></h1>
</body>
<script src="script.js"></script>
</html>
You need to set the sum again to 1 and also if you need to remove the input value, you need to set inp1.value to "". Check the code below.
let sum = 1;
function faktorial(){
let faktorial1 = +inp1.value
for(let i = 1; i < faktorial1; i++){
sum *=i+1
}
tpel.innerHTML = sum
sum = 1;
inp1.value = "";
}
<!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>
<input type="text" name="" id="inp1">
<!-- <input type="text" name="" id="inp2"> -->
<br>
<!-- <button onclick="show()">Print</button> -->
<button onclick="faktorial()">Faktorial</button>
<h1 id="tpel"></h1>
</body>
</html>
function faktorial(){
let sum = 1;
let faktorial1 = +inp1.value
for(let i = 1; i < faktorial1; i++){
sum *=i+1
}
tpel.innerHTML = sum
sum = null;
}
<!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>
<input type="text" name="" id="inp1">
<!-- <input type="text" name="" id="inp2"> -->
<br>
<!-- <button onclick="show()">Print</button> -->
<button onclick="faktorial()">Faktorial</button>
<h1 id="tpel"></h1>
</body>
<script src="script.js"></script>
</html>
Calculating factorial of a number is typical use-case of recursive function
function faktorial1() {
tpel.innerText = faktorial(inp1.value);
}
function faktorial(x) {
if (x == 0) {
return 1;
}
return x * faktorial(x - 1);
}
<input type="text" name="" id="inp1">
<button onclick="faktorial1()">Faktorial</button>
<h1 id="tpel"></h1>

Rotating Arrow between Two Points of Degrees

This is the fake gauge I want the arrow to work on
I want the red line/pointer to randomly generate between 0 - 100% humidity.
HTML:
//variables
let hygrometerHand = document.querySelector("#hygrometerHand");
const button = document.querySelector("#button");
let hygrometerAngle = 0;
hygrometerHand = 0;
//function
function generateResult() {
let min = -100;
let max = 95;
let x = Math.random() * (max - min) + min;
hygrometerHand = x;
hygrometerHand.style.transform = `rotate(${hygrometerHand}deg)`;
}
//button and event listener to generate moisture reading
button.addEventListener("click", generateResult);
<!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>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="clock-container">
<img src="https://i.stack.imgur.com/3z72xm.jpg" />
<div id="hygrometerHand"></div>
</div>
<div>
<button id="button">Click here</button>
</div>
<script src="main.js"></script>
</body>
</html>
Please help with this! I know the answer is probably going to be very simple but its my second week of learning JS in a bootcamp and my mind is p overloaded.
Thank you!

Categories