E-commerce template : function add cart shopping Js

Hi,

I created this simple e-commerce model and I’m having trouble adding the product to the cart.
I have created a counter function which must be displayed in a div that I added in the upper right corner where the shopper image is located, but my code does not work, the color of the button changes.

I have tried using getElementById it works but only for the first product, while the others does not work.

// to fix 
let addButton = document.querySelector("btn-add"),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
addButton.addEventListener("click", function(){
  
  const changeColorBtn = document.body.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    document.body.style.backgroundColor = "green";
  }
 else{
   document.body.style.backgroundColor = "#2c3632";
 }
  count += 1;
  shopping_cart.innerHTML = count  
});

This is my pen:

P.S . To anyone who answers me, would you suggest me to study DOM JS better?If you suggest me resources that are understandable and simple, I have been banging my head for a long time but I still struggle.

Thanks,
CamCode

I do not know what are you trying to grab from the HTML, but this line is trying to access the <body> tag, and not the button.

It is okay to use this, but its recomended to declare each variable individually so other people can read it easily.

Yes, it is recommended to study DOM JS if you want to make your website interactive, and if you want to manipulate the HTML DOM.

Like this ?

document.addButton.style.backgroundColor;

If you want to access the button, You already declared the variable up here

So you can just use the variable and not document, because document means to grab the whole document again.

addButton.style.backgroundColor;

Hello!

That’s because the querySelector is not actually querying the existing class, it’s instead querying for a tag called btn-add.

On the other hand, ids are meant to be unique, hence you should change the id attribute for class instead and using the class selector, not a tag. Look at these differences:

btn-add // This is a tag selector, like a div or any other tag.
#btn-add // This is an ID selector, querying the attribute id of a single element
.btn-add // this is a class selector, in other words, queries the class attribute.

Finally, there’s a difference between document.querySelector and document.querySelectorAll:

document.querySelectorAll('.btn-add') // Returns an array
document.querySelector('.btn-add') // Returns a single element

I hope it helps :slight_smile:,

Regards!

Edit

For a better understanding read this entry on CSS Selectors in the Free Code Camp Blog.

1 Like

Ok I fixed my code but doesn’t work yet

let addButton = document.querySelectorAll('.btn'),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
addButton.addEventListener("click", function(){
  
  const changeColorBtn = addButton.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    addButton.style.backgroundColor = "green";
  }
 else{
   addButton.style.backgroundColor = "#2c3632";
 }
  count += 1;
  shopping_cart.innerHTML = count  
});

:pensive:

Yes, I know, but try to understand what’s happening :slight_smile:.

let addButton = document.querySelectorAll('.btn');
// Remember that I said this returns an array?
// Arrays don't have an 'addEventListener' method.

Take a look a this code (you can see it working here):

<body>
<button id="special-button" class="btn">
One
</button>
<button class="btn">
Two
</button><button class="btn">
Three
</button>
<script>
/**
 * A simple function to display which target was clicked
 *
 * @param e The event data.
 */
function handleClick(e) {
	console.log('Element:', e.target);
}

const special = document.querySelector('#special');
const btns = document.querySelectorAll('.btn');

special.addEventListener('click', handleClick);

// Error! Arrays do not have the 'addEventListener' method:
// btns.addEventListener('click');

// Instead we must iterate the array and assign each
// button a listener:
btns.forEach(i => i.addEventListener('click', handleClick));
</script>
</body>

Read the comments and try to understand what happens :slight_smile:.

I also thought of iterating but it doesn’t work the same maybe I was wrong to write for loop.

let addButton = document.querySelectorAll('.btn'),
shopping_cart = document.getElementById("shopping-add"),
count = 0;
for(let i = 0; addButton.length; i++){
addButton.addEventListener("click", function(){
  const changeColorBtn = addButton.style.backgroundColor;
  if(changeColorBtn === '#2c3632'){
    addButton[i].style.backgroundColor = "green";
  }
 else{
   addButton[i].style.backgroundColor = "#2c3632";
 }
  count += 1
  shopping_cart.innerHTML = count
} 
)}


UPDATE: I resolved thanks to help from another

I was definitely wrong to write the loop condition I had to use foreach and not a simple loop and then I had to use textContent instead of innerHTML.

let addButtons = document.querySelectorAll(".btn"),
  shopping_cart = document.getElementById("shopping-add"),
  count = 0;

addButtons.forEach((addButton) => {
  addButton.addEventListener("click", function () {
    const changeColorBtn = addButton.style.backgroundColor;

    console.log(changeColorBtn);

    if (!changeColorBtn || changeColorBtn === "rgb(44, 54, 50)") {
      addButton.style.backgroundColor = "green";
    } else {
      addButton.style.backgroundColor = "rgb(44, 54, 50)";
    }

    count += 1;

    shopping_cart.textContent = count;
  });
});