0

i have a list of products (html article elements) on my website

var addToBasket = document.getElementsByClassName('add_to_basket')
var productSummary = document.getElementsByClassName('product_summary')
      for (var i=0; i < productSummary.length; i++){
        var productTitle = productSummary[i].children[1].innerHTML
        var productPrice = productSummary[i].children[2].innerHTML
        var productObject = {
          title: productTitle,
          price: productPrice,
          quantity: 1
        }
        productSummary[i].children[3].addEventListener('click', function(e){
          e.preventDefault();
          console.log(this, 'this');
          console.log(productObject, 'po4');
        })
      }

basically what this code does is find all the elements with that class, i then iterate over them and attach an event listener. each article has a button has one of it's children. when i click that button i am hoping it will return me that products details in my productObject. when i console.log(this) i get the button in that particular element. i.e when i click on product A it logs me the A element and when i click on product B it logs me the B element. however, when i console.log(productObject) it always logs me the last element (product B). how can i attach it so for each article it stores the details in the object correctly?

The Walrus
  • 958
  • 1
  • 17
  • 37
  • Use a closure: `for(...){ (function(i){ /* everything inside your for loop */ })(i); }` – blex Aug 13 '17 at 17:48
  • @blex so what is the closure solving here? – The Walrus Aug 13 '17 at 17:51
  • Change the callback function to an arrow function, and use `let` instead of `var` for the variables you want to use in the (asynchronous) callback. Read more in referenced Q&A. – trincot Aug 13 '17 at 17:52
  • With your current loop, your `i`, `productTitle`, and other variables are changed on each iteration, but remain the same variable. Once your loop is finished, when an event happens, the variable is equal to the last value that was set. Using a closure, you are creating a whole new scope, and thus new variables for each of the iterations. This way, they all get their different values. PS: I know, my explanation is very bad. – blex Aug 13 '17 at 17:54
  • @blex actually very clear explanation and has made a lot of sense, thanks! – The Walrus Aug 13 '17 at 18:19

0 Answers0