I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the id as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's id's color. But i wanna change all of them. How can i do this?
My Website
Console.log(i)
var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
function AddAllItemsToTable(TheMovies) {
movieNo = 0;
var counter = 0;
TheMovies.forEach(element => {
if (counter === 6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
var i = document.getElementsByClassName("fa fa-star")[element.movieId];
console.log(i);
if (element.movieScore >= 70) {
i.style.color = "deepskyblue"; //good movie
} else if (element.movieScore >= 50) {
i.style.color = "orange"; //not bad
} else {
i.style.color = "crimson"; //bad movie
}
counter++;
});
}
function getAllDataOnce() {
const dbRef = ref(db);
get(child(dbRef, "Movies"))
.then((snapshot) => {
var movies = [];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload = getAllDataOnce;
<div class="body" id="body">
<div class="baslik">Opening This Week</div>
<div class="baslik2">See all</div>
<div id="week">
</div>
<div class="baslik">Editor's Picks</div>
<div class="baslik2">See all</div>
<div id="editor">
</div>
</div>
I suggest to change the logic.
Your mistake is that you use the same id several times, and it should be unique (1 element = 1 unique id).
Try to make it like this:
// AddAllItemsToTable function
if (element.movieScore >= 50 && element.movieScore < 70 ) {
i.classList.add("deepskyblue"); // good movie
} else if (element.movieScore >= 70) {
i.classList.add("orange"); // not bad
} else {
i.classList.add("crimson"); // bad movie
}
After that, add the following rules to your styles file:
.deepskyblue {
color: deepskyblue;
}
.orange {
color: orange;
}
.crimson {
color: crimson;
}
Everything will work as it should and as a bonus it will be easier to manage styles and and you won't have to fix JS code for this.
Make a function
NOTE IDs need to be unique
const scoreColor = score => {
const color = "crimson"
if (score >= 70) return "deepskyblue"; //good movie
if (score >= 50) return "orange"; //not bad
return score;
};
function AddItemsToTable(name, score, img, id) {
const movies = `<div class="content">
<img src="${img}" >
<p>${name}</p>
<p><i class="fa fa-star"></i> <a class="${scoreColor(score)}">${score}</a></p>
</div>`;
body.innerHTML += movies;
body2.innerHTML += movies;
}
Related
I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the class as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's class's color. But i wanna change all of them. How can i do this?
var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
function AddAllItemsToTable(TheMovies) {
movieNo = 0;
var counter = 0;
TheMovies.forEach(element => {
if (counter === 6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
var i = document.getElementsByClassName("fa fa-star")[element.movieId];
console.log(i);
if (element.movieScore >= 70) {
i.style.color = "deepskyblue"; //good movie
} else if (element.movieScore >= 50) {
i.style.color = "orange"; //not bad
} else {
i.style.color = "crimson"; //bad movie
}
counter++;
});
}
function getAllDataOnce() {
const dbRef = ref(db);
get(child(dbRef, "Movies"))
.then((snapshot) => {
var movies = [];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload = getAllDataOnce;
<div class="body" id="body">
<div class="baslik">Opening This Week</div>
<div class="baslik2">See all</div>
<div id="week">
</div>
<div class="baslik">Editor's Picks</div>
<div class="baslik2">See all</div>
<div id="editor">
</div>
</div>
My Website
Console.log(i)
Instead of selecting the elements with class name you can give it a unique id. For th i tags you can give the id as for example id="star${id}"
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star${id}"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage,
element.movieId);
var i = document.getElementById("#star"+element.movieId);
you can just use a style="color:"desired color name/hexcode" easiest way to change color
Generates 26 buttons that have the value of every letter in the alphabet.
Then it adds an event listener to every button that should fetch results based on that button value and then displays them using displayMealCards.
Anywhere I add console.log(), I get results after I click an "alphabet Button" but they don't show up on my HTML page.
let alphabetContainer = document.querySelector(".alphabet-container");
// Alphabet Button HTML
function getAlphabetButtonHtml(letter) {
let alphabetButton = `<button class="letter-btn" value="${letter}">${letter}</button>`;
return alphabetButton;
}
// Add HTML Button to every letter in the alphabet
function getAlphabetButtonsHtml() {
let alphabetButtons = [];
for (i = 0; i < 26; i++) {
letter = String.fromCharCode(i + 65);
alphabetButtons.push(getAlphabetButtonHtml(letter));
}
return alphabetButtons;
}
function displayAlphabetButtons() {
alphabetContainer.innerHTML = `
<h2 class="section-title">Find recipes that start with:</h2>
<div class="alphabet-buttons">
${getAlphabetButtonsHtml().join("")}
</div>`;
}
displayAlphabetButtons();
// DISPLAY ALPHABET RESULTS
const letterButtons = document.querySelectorAll(".letter-btn");
// letterButtons is a HTML Collection. Add eventListener with forEach
letterButtons.forEach((letter) => {
letter.addEventListener("click", () => {
//call getRecipeCards to fetch the results and display them
getRecipeCards(letter.value).then(displayMealCards);
});
});
async function getRecipeCards(letter) {
const response = await fetch(
`https://www.themealdb.com/api/json/v1/1/search.php?f=${letter}`
);
const data = await response.json();
return data;
}
function displayMealCards(meals) {
let mealCardsContainer = document.querySelector(
".meal-card-results-container"
);
mealCardsContainer.innerHTML = `
<div class="meal-card-results">
${meals.meals.map((meal) => {
getMealCardHtml(meal);
})}
</div>`;
return mealCardsContainer;
}
function getMealCardHtml(meal) {
let mealCard = `
<div class="meal-card">
<h3 class="meal-card-title">${meal.strMeal}</h3>
</div>`;
return mealCard;
}
<div class="container alphabet-container"></div>
<div class="container meal-card-results-container">
</div>
Since you call getMealCardHtml(meal); from a function, you need return it's result:
let alphabetContainer = document.querySelector(".alphabet-container");
// Alphabet Button HTML
function getAlphabeButtonHtml(letter) {
let alphabetButton = `<button class="letter-btn" value="${letter}">${letter}</button>`;
return alphabetButton;
}
// Add HTML Button to every letter in the alphabet
function getAlphabetButtonsHtml() {
let alphabetButtons = [];
for (i = 0; i < 26; i++) {
letter = String.fromCharCode(i + 65);
alphabetButtons.push(getAlphabeButtonHtml(letter));
}
return alphabetButtons;
}
function displayAlphabetButtons() {
alphabetContainer.innerHTML = `
<h2 class="section-title">Find recipes that start with:</h2>
<div class="alphabet-buttons">
${getAlphabetButtonsHtml().join("")}
</div>`;
}
displayAlphabetButtons();
// DISPLAY ALPHABET RESULTS
const letterButtons = document.querySelectorAll(".letter-btn");
// letterButtons is a HTML Collection. Add eventListener with forEach
letterButtons.forEach((letter) => {
letter.addEventListener("click", () => {
//call getRecipeCards to fetch the results and display them
getRecipeCards(letter.value).then(displayMealCards);
});
});
async function getRecipeCards(letter) {
const response = await fetch(
`https://www.themealdb.com/api/json/v1/1/search.php?f=${letter}`
);
const data = await response.json();
return data;
}
function displayMealCards(meals) {
let mealCardsContainer = document.querySelector(
".meal-card-results-container"
);
mealCardsContainer.innerHTML = `
<div class="meal-card-results">
${meals.meals.map((meal) => {
return getMealCardHtml(meal);
})}
</div>`;
return mealCardsContainer;
}
function getMealCardHtml(meal) {
let mealCard = `
<div class="meal-card">
<a href="#"
><img
src="./uuuspp1468263334.jpg"
alt="food"
class="meal-card-img"
/></a>
<h3 class="meal-card-title">${meal.strMeal}</h3>
<div class="meal-card-meta">
Chicken
<a href="#" class="meal-card-flag-link"
><img
src="./flags/Mexican.png"
alt="Mexican"
class="flag-img meal-card-flag-img"
/></a>
</div>
<p class="meal-card-intro">
Put your wine, shallot, herbs and peppercorns into a small pot and
bring to the boil, then simmer slowly for...
</p>
Read More
</div>`;
return mealCard;
}
<div class="container alphabet-container"></div>
<div class="container meal-card-results-container">
</div>
If you remove the innermost braces from
meals.meals.map((meal) => { getMealCardHtml(meal); }) or add return after the opening brace, the map will result in something to work with. In other words, the current lambda for meals.meals.map does not return anything.
Aside: you can use event delegation to avoid adding 26 handler functions. A minimal reproducable example:
document.addEventListener(`click`, handle);
const alphabetContainer = document.querySelector(`.alphabet-container`);
for (let i = 65; i < 91; i += 1) {
alphabetContainer.insertAdjacentHTML(
`beforeend`,
`${i%13 == 0 ? `<br>` : ``}<button data-letter="${String.fromCharCode(i)}">${
String.fromCharCode(i)}</button>`
);
}
function handle(evt) {
if (evt.target.dataset.letter) {
return getRecipeCards(evt.target.dataset.letter);
}
}
async function getRecipeCards(letter) {
const response = await
fetch(`https://www.themealdb.com/api/json/v1/1/search.php?f=${letter}`)
.then(r => r.json())
.then(r => writeResult(r, letter));
}
function writeResult(recipes, letter) {
const resultContainer = document.querySelector(`.meal-card-results-container`);
resultContainer.textContent = ``;
resultContainer.insertAdjacentHTML(
`beforeend`,
`<h3>Meals (${letter})</h3>`);
recipes.meals.forEach( meal =>
resultContainer.insertAdjacentHTML(
`beforeend`,
`<div>${meal.strMeal}</div>`)
);
}
body {
font: normal 12px/15px verdana, arial, sans-serif;
margin: 2rem;
}
button {
margin: 2px 2px 0;
font-family: 'courier new';
}
<div class="container alphabet-container"></div>
<div class="container meal-card-results-container"></div>
I have this simple function that will create a paragraph.
function appendElements() {
const input = document.getElementById("myInput");
const createDiv = document.createElement("div");
createDiv.classList.add("myDiv");
const createP = document.createElement("P");
createP.classList.add("myParagraph");
createP.innerHTML = input.value;
createDiv.appendChild(createP);
const div = document.getElementById("examplediv");
div.appendChild(createDiv);
}
And another function that will sum the innerHTML of the divs, and create a div element for the result.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
const createElement = document.createElement("div");
createElement.innerHTML = sumArray;
document.getElementById("divForAvg").appendChild(createElement);
}
And the last function that will change the innerHTML of the paragraph element when clicked.
function editELement() {
const input2 = document.getElementById("myInput2")
let items = document.getElementsByClassName("myParagraph");
for(var i = 0; i < items.length; i++){
items[i].onclick = function(){
items[i].innerHTML = input2.value;
}
}
}
So basically when I create some paragraphs and execute the second function, the second function will calculate the sum of the paragraphs and create a div with the sum inside.
What I want is when I remove one of the paragraph elements or edit them, I want the previously created divs to update(recalculate the sum), I have literally no idea on how to do this.
Let's try this using event delegation. I have interpreted what I think you are looking for (note: it's exemplary, but it may give you an idea for your code) and reduced your code a bit for the example. Note the 2 different ways to create new elements (insertAdjacentHTML and Object.assign).
You can play with the code #Stackblitz.com.
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.id === "create") {
return appendInputValueElement();
}
if (evt.target.classList.contains("remove")) {
return removeThis(evt.target);
}
if (evt.target.id === "clear") {
document.querySelector("#accumulated ul").innerHTML = "";
return true;
}
}
function appendInputValueElement() {
const input = document.querySelector(".myInput");
const div = document.querySelector("#exampleDiv");
exampleDiv.insertAdjacentHTML("beforeEnd", `
<div class="myDiv">
<button class="remove">remove</button>
<span class="myParagraph">${input.value || 0}</span>
</div>
`);
calculateSum();
}
function removeThis(elem) {
elem.closest(".myDiv").remove();
calculateSum();
}
function calculateSum() {
const allParas = [...document.querySelectorAll(".myParagraph")];
const sum = allParas.reduce( (acc, val) => acc + +val.textContent, 0);
document.querySelector("#accumulated ul")
.append(Object.assign(document.createElement("li"), {textContent: sum}));
document.querySelector(".currentSum").dataset.currentSum = sum;
if (sum < 1) {
document.querySelector("#accumulated ul").innerHTML = "";
}
}
.currentSum::after {
content: ' 'attr(data-current-sum);
color: green;
font-weight: bold;
}
.myParagraph {
color: red;
}
.accSums, .currentSum, .myDiv {
margin-top: 0.3rem;
}
<div>
A number please: <input class="myInput" type="number" value="12">
<button id="create">create value</button>
</div>
<div class="currentSum" data-current-sum="0">*Current sum</div>
<p id="exampleDiv"></p>
<div id="accumulated">
<div class="accSums">*Accumulated sums</div>
<ul></ul>
<button id="clear">Clear accumulated</button>
</div>
i've changed calculateSum you can call it when you edited paragraph. If summParagraph doesn't exists then we create it.
function calculateSum() {
let div = document.getElementsByClassName("myParagraph");
let array = new Array;
for (var i = 0; i <div.length; i++) {
array.push(div[i].innerHTML);
}
let numberedArray = array.map((i) => Number(i));
const sumArray = numberedArray.reduce(function(a, b){
return a + b;
}, 0);
if (!document.getElementById("summParagraph")) {
const createElement = document.createElement("div");
createElement.setAttribute("id", "summParagraph");
document.getElementById("divForAvg").appendChild(createElement);
}
document.getElementById("summParagraph").innerHTML = summArray;
}
I am trying to create a changing text for every 3 seconds. But it seems just to run once and then it stops doing anything. My code:
HTML
<div class="output">
<h2>True Multi-Purpose Theme for
<span class="changingtext">Business</span>
and More
</h2>
</div>
JavaScript
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML = 'Business'){
newText.innerHTML = 'Agencies';
}
else if (newText.innerHTML = "Agencies"){
newText.innerHTML = 'Startups';
}
else {
newText.innerHTML = 'Business';
}
}, 3000)
The problem is that you are using assignation instead of comparaison in your if
WRONG
if(newText.innerHTML = 'Business'){
CORRECT
if (newText.innerHTML === 'Business') {
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML === 'Business') {
newText.innerHTML = 'Agencies';
} else if (newText.innerHTML === "Agencies") {
newText.innerHTML = 'Startups'
} else {
newText.innerHTML = 'Business'
}
}, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
Also, the following could be better :
const text = document.querySelector('.changingtext')
const texts = [
'Business',
'Agencies',
'Startups',
];
function nextText() {
const actualTextIndex = texts.findIndex(x => text.innerText === x);
const newTextIndex = actualTextIndex + 1 === texts.length ? 0 : actualTextIndex + 1;
text.innerText = texts[newTextIndex];
}
setInterval(nextText, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
You can improve it again by :
Creating an utility function that will work in standalone getting the selector, the time between a text change and the list of texts to loop from
Gl
I am using a foreach loop in php to load data from a mysql table. I'm using the data ID's loaded from the data base and applying it to the button values.
The buttons come in two colors, green and white. The buttons represent likes for liking comments or posts.
The total existing number of likes starts at 6 (div id="total")
white buttons
If button 1 has color of white and you click it, total likes (6) will increase by 1. If you click button 1 again, total likes (7) will decrease by 1.
If button 1, button 2, and button three are clicked, total likes (6) increases by 3 ( 1 for each button). If button 1, button 2 and button 3 are clicked again, the total likes (9) will decrease by 3.
The Puzzle
Green buttons
How do I make it so, When a green button is clicked, the total (6) decrease by 1, and if the button is clicked again, it should increase by 1. Unlike white buttons.
If Green button 3, 5 and 6 are clicked, the total (6) should decease by 3. if the same buttons are clicked again, total (6) increases by 3.
Here is my code
var colorcode = "rgb(116, 204, 49)";
var buttonid = str;
var elem = document.getElementById(buttonid);
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
var likes = new Array();
function showUser(str) {
////// 1st condition /////
if (theCSSprop == colorcode) {
if (likes[value] == 0 || !likes[value]) {
likes[value] = 1;
} else {
likes[value] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum--
}
}
}
////// 2nd condition /////
else {
if (likes[str] == 0 || !likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum++
}
}
}
var tot = initialtotal + sum;
document.getElementById("total").innerHTML = tot;
}
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>
<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this.value)">LIKE </button>
<button id="346" value="346" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="128" value="128" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="687" value="687" onclick="showUser(this.value)">LIKE </button>
<button id="183" value="183" onclick="showUser(this.value)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="555" value="555" onclick="showUser(this.value)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->
Instead of passing this.value to showUser(), just pass this. That way, the function can get the value and the style directly, without having to call getElementById() (you're not passing the ID). Then you need to set theCSSprop inside the function, so it's the property of the current button.
To make green buttons alternate direction from increment to decrement, you need a global variable that remembers what it did the last time the function was called.
Also, you don't need to write if(likes[str] == 0 || !likes[str]), since 0 is faley. Just write if(!likes[str]).
var colorcode = "rgb(116, 204, 49)";
var likes = new Array();
var greenIncr = -1;
function showUser(elem) {
var initialtotal = parseInt(document.getElementById("total").innerHTML, 10);
////// 1st condition /////
var str = elem.value;
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
if (theCSSprop == colorcode) {
if (!likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum += greenIncr;
}
}
greenIncr = -greenIncr; // revese the direction of green button
}
////// 2nd condition /////
else {
if (!likes[str]) {
likes[str] = 1;
} else {
likes[str] = 0;
}
var sum = 0;
for (i = 0; i < likes.length; i++) {
if (likes[i] == 1) {
sum++
}
}
}
var tot = initialtotal + sum;
document.getElementById("total").innerHTML = tot;
}
<div id="total" style="width:100px;padding:50px 0px; background-color:whitesmoke;text-align:center;">6 </div>
<!---------------------------------------------------------------------------------------------------------------------->
<button id="5" value="5" onclick="showUser(this)">LIKE </button>
<button id="346" value="346" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="128" value="128" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="687" value="687" onclick="showUser(this)">LIKE </button>
<button id="183" value="183" onclick="showUser(this)" style="background-color:rgb(116, 204, 49);">LIKE </button>
<button id="555" value="555" onclick="showUser(this)">LIKE </button>
<!---------------------------------------------------------------------------------------------------------------------->
First naive implementation can look like this
class Counter {
constructor(initial) {
this.initial = initial
this.white = [false, false, false]
this.green = [false, false, false]
}
changeGreen(index) {
this.green[index] = !this.green[index]
}
changeWhite(index) {
this.white[index] = !this.white[index]
}
get total() {
return this.initial + this.white.reduce((total, current) => total + current, 0) + this.green.reduce((total, current) => total - current, 0)
}
}
let counter = new Counter(6)
const render = counter => {
document.querySelector('#total').innerHTML = counter.total
}
render(counter)
;['#first', '#second', '#third'].map((selector, index) => {
document.querySelector(selector).addEventListener('click', e => {
e.target.classList.toggle('pressed')
counter.changeWhite(index)
render(counter)
})
})
;['#fourth', '#fifth', '#sixth'].map((selector, index) => {
document.querySelector(selector).addEventListener('click', e => {
e.target.classList.toggle('pressed')
counter.changeGreen(index)
render(counter)
})
})
.green {
background: #00aa00
}
.pressed {
border-style: inset
}
<div id="total">0</div>
<p>
<button id="first">First</button>
<button id="second">Second</button>
<button id="third">Third</button>
<button id="fourth" class="green">Fourth</button>
<button id="fifth" class="green">Fifth</button>
<button id="sixth" class="green">Sixth</button>
</p>
But after all I've finished with something like
class Counter {
constructor(initial, strategy) {
this.initial = initial;
this.elements = [];
this.strategy = typeof strategy === 'function' ? strategy : () => {}
}
addElement(content, type, next) {
const element = {
content: content,
type: type,
state: false
};
this.elements.push(element);
return next(element, this.elements.length - 1);
}
toggleElementState(index) {
this.elements[index].state = !this.elements[index].state
}
get total() {
return this.strategy(this.initial, this.elements)
}
}
const initialize = () => {
Counter.WHITE = Symbol('white');
Counter.GREEN = Symbol('green');
const counter = new Counter(6, (initial, buttons) => {
return initial +
buttons.filter(button => button.type === Counter.WHITE).reduce((total, current) => total + Number(current.state), 0) +
buttons.filter(button => button.type === Counter.GREEN).reduce((total, current) => total - Number(current.state), 0)
});
const render = counter => {
document.querySelector('#total').innerHTML = counter.total
};
const createButton = (element, index) => {
const button = document.createElement('button');
button.setAttribute('data-id', index);
button.classList.add(element.type === Counter.GREEN ? 'green' : 'none');
button.textContent = element.content;
document.querySelector('#buttons').appendChild(button)
};
const addButton = (type, ...selectors) => {
selectors.forEach(selector => counter.addElement(selector, type, createButton));
};
render(counter);
addButton(Counter.WHITE, '#first', '#second', '#third');
addButton(Counter.GREEN, '#fourth', '#fifth', '#sixth');
addButton(Counter.WHITE, '#first', '#second', '#third');
document.querySelector('#buttons').addEventListener('click', function(e) {
e.target.classList.toggle('pressed');
counter.toggleElementState(parseInt(e.target.dataset.id));
render(counter)
})
};
document.addEventListener('DOMContentLoaded', initialize);
.green {
background: #00aa00
}
.pressed {
border-style: inset
}
<div id="total">0</div>
<p id="buttons">
</p>