For loop through different IDs with JS? - javascript

So I have 30 buttons (id="button1" to "button30"):
<button type="button" class="buttons" id="button1">1</button>
and I set up some JS so that the button changes colors on every click:
let index = 0;
const colors = ['green', 'red', '#405cf5'];
let btn = document.querySelector('#button1');
document.querySelector('#button1').addEventListener('click', function(){
btn.style.backgroundColor = colors[index];
index = index >= colors.length - 1 ? 0 : index + 1;
})
I'm not sure how to set this up so that all my buttons do this without copy and pasting and manually typing out the ID each time.

Delegate, please.
Here I find the closest static container of the buttons (if no container use document) and any click inside the container is checked against the thing we want clicked - you can test against any valid selector.
let index = 0;
const colors = ['green', 'red', '#405cf5'];
document.getElementById("buttonContainer").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.matches("button.buttons")) {
tgt.style.backgroundColor = colors[index++ % colors.length];
}
})
<div id="buttonContainer">
<button type="button" class="buttons" id="button1">1</button>
<button type="button" class="buttons" id="button2">2</button>
<button type="button" class="buttons" id="button3">3</button>
</div>
If there are other buttons not to be affected we can use a class
let index = 0;
const colors = ['green', 'red', '#405cf5'];
document.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.matches("button.buttons")) {
tgt.style.backgroundColor = colors[index++ % colors.length];
}
})
<button type="button" class="buttons" id="button1">1</button>
<button type="button" class="buttons" id="button2">2</button>
<button type="button" class="buttons" id="button3">3</button>
<button class="otherbutton">Dont color me</button>

Related

How do you use several variables and get several answers from one function in JavaScript?

I've been learning JavaScript for a college assignment and I can't figure out why my point counters don't work.
<HTML>
<HEAD>
<TITLE>Team points counter</TITLE>
<script>
<!-- Variable assignments brick -->
var T1, T2, T3, T4, T5;
T1 = 0;
T2 = 0;
T3 = 0;
T4 = 0;
T5 = 0;
<!-- Function brick -->
function Add(Tx, TxAns) {
return function() {
Tx += 1;
document.getElementById("TxAns").innerHTML = Tx;
}
}
function Sub(Tx,TxAns) {
return function() {
Tx += 1;
document.getElementById("TxAns").innerHTML = Tx;
}
}
</script>
</HEAD>
<BODY>
<h1 id="Subtitle">Team points counter</h1>
<!-- Button brick -->
<p id = "T1p"> Team 1 &nbsp
<button id=Team1A type="button" onclick="Add(T1,T1Ans);"> +1 </button>
<button id=Team1S type="button" onclick="Sub(T1,T1Ans);"> -1 </button> </p>
<p> <output id="T1Ans"> </output> </p>
<p id = "T2p"> Team 2 &nbsp
<button id=Team2A type="button" onclick="Add(T2,T2Ans);"> +1 </button>
<button id=Team2S type="button" onclick="Sub(T2,T2Ans);"> -1 </button> </p>
<p> <output id="T2Ans"> </output> </p>
<p id = "T3p"> Team 3 &nbsp
<button id=Team3A type="button" onclick="Add(T3,T3Ans);"> +1 </button>
<button id=Team3S type="button" onclick="Sub(T3,T3Ans);"> -1 </button> </p>
<p> <output id="T3Ans"> </output> </p>
<p id = "T4p"> Team 4 &nbsp
<button id=Team4A type="button" onclick="Add(T4,T4Ans);"> +1 </button>
<button id=Team4S type="button" onclick="Sub(T4,T5Ans);"> -1 </button> </p>
<p> <output id="T4Ans"> </output> </p>
<p id = "T5p"> Team 5 &nbsp
<button id=Team5A type="button" onclick="Add(T5,T5Ans);"> +1 </button>
<button id=Team5S type="button" onclick="Sub(T5,T5Ans);"> -1 </button> </p>
<p> <output id="T5Ans"> </output> </p>
</BODY>
<script>
<!-- CSS brick -->
document.body.style.backgroundColor = "grey";
document.getElementById("Subtitle").style.color = "Black";
document.getElementById("T1p").style.color = "red";
document.getElementById("T2p").style.color = "orange";
document.getElementById("T3p").style.color = "yellow";
document.getElementById("T4p").style.color = "green";
document.getElementById("T5p").style.color = "blue";
</script>
</HTML>
I tried making a different program to figure out why at it seems that when I try to make the function availible for several variables, it stops working.
<HTML>
<SCRIPT>
T1 = 0;
function Add(Tx){
Tx += 1;
document.getElementById("Tx").innerHTML = Tx;
}
</SCRIPT>
<BUTTON type="button" onclick="Add(T1);"> +1 </BUTTON>
<OUTPUT id=Tx> </OUTPUT>
</HTML>
Now this only allows itself to be added to once.
Any and all help would be appreciated
Below is an example of using an Object to keep track of the totals.
I've also modified you code to be a bit more DRY. Instead of creating lots of HTML for each one, I place the HTML inside a hidden DIV to act like a template, and then use Javascript to create the real ones. From here I can then easily attach the event to the buttons.
const answers = {
T1: 0, T2: 0, T3: 0, T4: 0, T5: 0
};
const mount = document.querySelector('#mount');
const template = document.querySelector("#team_template");
function TeamInput(o) {
const f = document.createElement('div');
f.innerHTML = template.innerHTML;
const p = f.querySelector('p');
p.style.color = o.color;
const output = f.querySelector('output');
const buttons = p.querySelectorAll('button');
f.querySelector('span').innerText = o.name;
//add button
buttons[0].addEventListener('click', () => {
answers[o.T] += 1;
console.log(answers);
output.innerText = answers[o.T];
});
//substract
buttons[1].addEventListener('click', () => {
answers[o.T] -= 1;
output.innerText = answers[o.T];
});
//add to DOM
mount.appendChild(f);
}
document.body.style.backgroundColor = "grey";
document.getElementById("Subtitle").style.color = "Black";
TeamInput({name: 'Team 1', color: 'red', T: 'T1'});
TeamInput({name: 'Team 2', color: 'orange', T: 'T2'});
TeamInput({name: 'Team 3', color: 'yellow', T: 'T3'});
TeamInput({name: 'Team 4', color: 'green',T: 'T4'});
TeamInput({name: 'Team 5', color: 'blue',T: 'T5'});
<h1 id="Subtitle">Team points counter</h1>
<div id="mount"></div>
<div id="team_template" style="display:none">
<p><span>Name</span>&nbsp
<button type="button"> +1 </button>
<button type="button"> -1 </button>
</p>
<p>
<output>0</output>
</p>
</div>

how to increase value with button click on javascript

I am learning javaScript. I have created a simple app, that when I click the button every time I want to increase the value.
let btn = document.querySelector(".btn");
btn.addEventListener("click", () => {
addCart();
});
function addCart() {
let btnn = (document.querySelector(".cart span").textContent = 1);
}
<ul class="cart">
cart
<span>(0)</span>
</ul>
<input type="button" value="click" class="btn" />
Add a count variable and increment it by one on every click:
let btn = document.querySelector(".btn");
let count = 0;
btn.addEventListener("click", () => {
addCart();
});
function addCart() {
count++;
document.querySelector(".cart span").textContent = `(${count})`;
}
<ul class="cart">
cart
<span>(0)</span>
</ul>
<input type="button" value="click" class="btn" />

Add specific items to cart on click

I want the cart to add the item that the Add to cart button relates to. Can you also please explain the reason behind it not working. Currently it is only adding the first product.
Here is the HTML:
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
and here is the JavaScript:
const name = document.querySelectorAll(".name");
const price = document.querySelectorAll("#price");
const button = document.querySelectorAll("button");
const cart = []
const addToCart = () => {
for (var i = 0; i < 1; i++) {
cart.push(name[i].innerText)
cart.push(parseInt(price[i].innerText))
}
console.log(cart)
}
Thank you
Here is an example, where we use data- attributes in the html. To help us when we load the cart.
let buttons = document.getElementsByTagName("button");
const cart = [];
for(var i=0; i<buttons.length; i++) {
let button = buttons[i];
console.log(button);
button.addEventListener('click', function(event){
console.clear();
console.log(event.target);
console.log(event.target.dataset.productSku);
cart.push( event.target.dataset.productSku );
console.log(cart)
});
}
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<button data-product-sku="ps4black">Add to cart</button>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<button data-product-sku="xboxoneblack">Add to cart</button>
<div id="cart"></div>

how to click multiple buttons in a row with javascript?

is it possible to create script that click multiple buttons in a row with x time interval between clicks ?
for example when first button is clicked after x time second is clicked and etc.
(using Javascript).
var inputs = document.getElementsByClassName('className');
for(var i=0; i<inputs.length;i++) {
setInterval(function()
{inputs[i].click() },1000
}
use this code
var allButtons = document.getElementsByClassName("button")
var timeInterval = 5000 // x time in miliseconds
function pressButton(iteration=0){
setTimeout(function(){
allButtons[iteration].click();
pressButton(iteration++);
}, timeInterval)
}
pressButton();
<div id="parent">
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
</div>
More can be helped if you paste your code
var clickcallback = function(i) {
setTimeout(function() {
let id = "button" + i;
document.getElementById(id).click();
}, 1000); // one second
if(i <= 3) {
clickcallback(i+1);
}
};
<div>
<button id="button1" onClick="alert('click button1');">Button 1</button>
<button id="button2" onClick="alert('click button2');">Button 2</button>
<button id="button3" onClick="alert('click button3');">Button 3</button>
</div>
Here the demo:
https://jsfiddle.net/frasim/730xmhfv/8/

Buttons display progress

I'm doing a project for parent with a newborn Child, where they can progress in their learning taking care of their Child. This will be shown with buttons, and when a stage is complete, it will change the color on that button.
My code so far looks like this:
To change the buttons color to green.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button" value = "Instructed" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done with help" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done by yourself" style= "color:black" onclick="setColor('button', '#101010')";/>
</div>
</div>
When I Click the first button "Instructed" the color change to green (As I want it to). But when I click anyother button, the first button once again goes green and the other goes blue?
How can I fix it so whatever button they click on, will be colored green?
You gave every button the same id - an id should be identifying, which in this case it isn't. Your code here, takes the first element with the id button which is why the first button changes everytime.
Either use different ids for each individual button, or access the clicked element itself through the event-variable.
You also have only one count-variable, which won't work with multiple buttons. Imagine you pressing the first button => count is now 1. You then press the second button, it wouldn't turn green, as count is already 1.
You should probably store that information on the element itself, probably with a data-count-attribute.
Here is a working example:
function setColor(element) {
if(!element.hasAttribute('data-count')){
element.setAttribute('data-count', 1);
}
var count = element.getAttribute('data-count');
if(count == 0){
element.style.backgroundColor = '#ffffff';
element.setAttribute('data-count', 1);
}else{
element.style.backgroundColor = '#7fff00';
element.setAttribute('data-count', 0);
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" value = "Instructed" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done with help" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done by yourself" style= "color:black" onclick="setColor(this)";/>
</div>
</div>
So lets remove those duplicate ID's, and then we can actually pass the element into the function directly so we don't need to grab it by it's ID.
Then instead of using a count variable, we store value on the actual element in a data attribute so that it's state is stored on the element itself.
function setColor(element) {
if (element.getAttribute('data-done') === "0") {
element.style.backgroundColor = "#7FFF00"
element.setAttribute('data-done', "1");
} else {
element.style.backgroundColor = "#FFFFFF"
element.setAttribute('data-done', "0");
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button1" value="Instructed" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button2" value="Done with help" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button3" value="Done by yourself" style="color:black" onclick="setColor(this)" data-done="0" />
</div>
</div>
Although perhaps the most semantic way would be to use classes and add an event listener:
// Grab all the buttons by their class
var btns = document.querySelectorAll('.btn-diaper');
// Loop through the buttons
for (var i = 0; i < btns.length; i++) {
// Assign a click listener to each button
btns[i].addEventListener("click", function(event) {
var el = event.toElement;
// Toggle the "active" class, which changes the button styling
if (el.classList.contains('active')) {
el.classList.remove('active');
} else {
el.classList.add('active');
}
});
}
.btn-diaper {
color: black;
background-color: #fff;
}
.btn-diaper.active {
background-color: #7fff00;
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input class="btn-diaper" type="button" id="button1" value="Instructed" />
<input class="btn-diaper" type="button" id="button2" value="Done with help" />
<input class="btn-diaper" type="button" id="button3" value="Done by yourself" />
</div>
</div>

Categories