loop over elements in div - javascript

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)
}

Related

JavaScript: Repeated EventListener when created in a for loop

my code depends on creating an EventListener inside a loop then removing it after the function is done, yet somehow on the Eventlitesning is repeated after each loop execution, my code looks something like:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link href="css/style.css" rel="stylesheet"> -->
</head>
<body>
<button id="btn" onclick="fun()">button</button>
</body>
<script>
const btn=document.getElementById("btn");
console.log(btn);
function fun(){
for (let i = 0; i < 5; i++) {
btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
//code to be executed
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
}
}
</script>
</html>
the first time I press the button the 5 warning messages appear and the second time I press the button the 5 warnings messages appear twice, an dun the third time it appears 3 times, and so on.
I'd be very grateful if anyone could support me in this issue.
I tried to do the following but it didn't work either:
const btn=document.getElementById("btn");
function fun(){
for (let i = 0; i < 5; i++) {
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
btn.addEventListener("click", ()=>{alert(`warning NO.${i}`)});
//code to be executed
btn.removeEventListener("click", ()=>{alert(`warning NO.${i}`)});
}
}
Does this code satisfy your requirement?
Note: onclick() itself is an event listener.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link href="css/style.css" rel="stylesheet"> -->
</head>
<body>
<button id="btn" onclick="fun()">button</button>
</body>
<script>
function fun(){
for (let i = 0; i < 5; i++) {
alert(`warning NO.${i}`);
}
}
</script>
</html>

I'm trying 2 create a slideshow in JavaScript

I'm trying to create an automatic slideshow in HTML and JavaScript, but the code is making my entire webpage blank.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="4.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="landing slides">
<div class="slides">
<img src="effiel tower.png" alt="">
<img src="Capetown.png" alt="">
<img src="china mountain.png" alt="">
</div>
</div>
The images on the HTML are working fine, but as soon as I enter the JavaScript code it gives me a blank page.
<script>
window.onload = function(){
var index = 0;
show ();
function show(){
var i;
var slides = document.getElementsByClassName("slides");
for(i=0;i<slides.length; i++){
slides[i].style.display ="none"
}
index=index + 1;
if(index>slides.length){
index=1;
}
slides[index-1].style.display = "block";
setTimeout(show, 1500);
}
}
</script>
</body>
</html>
you selected the parent of the images. It means you are hiding parent. Not images. add class to your images and select them by getElementsByClassName.
let index = 0;
const slides = document.querySelectorAll('.slides > img');
function showSlideAt(index) {
for(let i=0;i<slides.length; i++){
const slide = slides[i];
slide.style.display = i === index ? "block" : "none";
}
}
showSlideAt(0);
setInterval(() => {
index = (index + 1) % slides.length;
showSlideAt(index);
}, 1500)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="4.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="landing slides">
<div class="slides">
<img src="https://www.gravatar.com/avatar/12a357d653e4cf98f3d3f06f122c2c1f?s=64&d=identicon&r=PG" height="100">
<img src="https://www.gravatar.com/avatar/fd4522e30ca42954b37fcc3b4072c3f9?s=48&d=identicon&r=PG&f=1" height="100">
</div>
</div>
</body>
</html>

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!

How to return button's value on click?

I'm looking to update a text block with the value of a button, but I'm not sure how to get the value from the function for use.
var allButtons = document.querySelectorAll('div[class^=digits]');
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function current() {
let current = this.innerText;
console.log(current);
return current;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class='container'>
<div class='calculator'>
<div class='window'>
<input type="text" class="window" name="display" id="display" id='window'>
</div>
<div class='digits'><button>7</button></div>
<div class='digits'><button>8</button></div>
<div class='digits'><button>9</button></div>
<div class='digits'><button>4</button></div>
<div class='digits'><button>5</button></div>
<div class='digits'><button>6</button></div>
<div class='digits'><button>1</button></div>
<div class='digits'><button>2</button></div>
<div class='digits'><button>3</button></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
The buttons don't have a value, but they do have textContent. Update the textbox with that instead. Also don't name or return from the function, there's no point.
var allButtons = document.querySelectorAll('div[class^=digits]');
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function () {
document.querySelector('input').value = this.textContent;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class='container'>
<div class='calculator'>
<div class='window'>
<input type="text" class="window" name="display" id="display" id='window'>
</div>
<div class='digits'><button>7</button></div>
<div class='digits'><button>8</button></div>
<div class='digits'><button>9</button></div>
<div class='digits'><button>4</button></div>
<div class='digits'><button>5</button></div>
<div class='digits'><button>6</button></div>
<div class='digits'><button>1</button></div>
<div class='digits'><button>2</button></div>
<div class='digits'><button>3</button></div>
</div>
</div>
</body>
</html>
You can do like that
<div class="digits">
<button onclick="setValue(7)">7</button>
</div>
function setValue(value) {
let input = document.querySelector("input");
input.value = value;
}
Be careful with the input it has 2 ids
this should get you started
var allButtons = document.querySelectorAll('div[class^=digits]');
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function () {
var display= document.getElementById('display');
console.log(this.getElementsByTagName('button')[0].innerHTML);
display.value = this.getElementsByTagName('button')[0].innerHTML;
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div class='container'>
<div class='calculator'>
<div class='window'>
<input type="text" class="window" name="display" id="display" id='window'>
</div>
<div class='digits'><button>7</button></div>
<div class='digits'><button>8</button></div>
<div class='digits'><button>9</button></div>
<div class='digits'><button>4</button></div>
<div class='digits'><button>5</button></div>
<div class='digits'><button>6</button></div>
<div class='digits'><button>1</button></div>
<div class='digits'><button>2</button></div>
<div class='digits'><button>3</button></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Use myTextInput.value to change the value of a text input field
Also your
Also your text input has 2 ids, you need to get the DOM object of your text input and change its .value, this should work
var allButtons = document.querySelectorAll('div[class^=digits]');
let textField = document.getElementById("display"); // Get Text Input Field from HTML
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function current() {
let current = this.innerText;
textField.value = current; // Change TextInput Value
console.log(current);
return current;
});
}

My JS code is still keep saying nothing(?) instead of the correct rgb colors, and don't know why?

Well, I want to make an rgb color guessing game in JS (+HTML,CSS) and in the for loop, the next line is giving me just space back:
console.log(this.style.background);
Here is the full JS code:
var colors = document.querySelectorAll(".square");
var rgbColors = [
"rgb(21,54,217)",
"rgb(32,255,0)",
"rgb(43,255,255)",
"rgb(32,68,103)",
"rgb(147,54,24)",
"rgb(255,54,217)"
];
var pickedColor = rgbColors[3];
var colorDisplay = document.querySelector("#colorDisplay");
colorDisplay.textContent = pickedColor;
for (var i = 0; i < colors.length; i++) {
colors[i].style.backgroundColor = rgbColors[i];
colors[i].addEventListener("click", function() {
console.log(this.style.background);
})
}
And here is my HTML if it's necessary:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RGB guessing game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> guessing game</h1>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<link rel="stylesheet" type="text/css" media="screen" href="rgbGame.css" />
<script src="rgbGame.js"></script>
</body>
</html>
I guess my CSS is not the source of the problem.
Hope you can help me. Thanks, Kristof.
Since background wasn't set, it will be an empty string.
Use console.log(this.style); to show all style properties. You will be able to see that background is an empty string and that backgroundColor contains a string representing the colour information you set earlier.
Element.style.background does not exist and you have not set it for any Element; use Element.style.backgroundColor.
var colors = document.querySelectorAll(".square");
var rgbColors = [
"rgb(21,54,217)",
"rgb(32,255,0)",
"rgb(43,255,255)",
"rgb(32,68,103)",
"rgb(147,54,24)",
"rgb(255,54,217)"
];
var pickedColor = rgbColors[3];
var colorDisplay = document.querySelector("#colorDisplay");
colorDisplay.textContent = pickedColor;
for (var i = 0; i < colors.length; i++) {
colors[i].style.backgroundColor = rgbColors[i];
colors[i].addEventListener("click", function() {
console.log(this.style.backgroundColor);
})
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RGB guessing game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> guessing game</h1>
<div id="container">
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
<div class="square">4</div>
<div class="square">5</div>
<div class="square">6</div>
</div>
<link rel="stylesheet" type="text/css" media="screen" href="rgbGame.css" />
<script src="rgbGame.js"></script>
</body>
</html>

Categories