0

I want to create a cookie which will remember a product that costumer wants to add to wish list. Every product and button which is named heart in code has its specific array value which is f. For some reason this code doesnt create a cookie:

var hearts=document.getElementsByClassName("heart");
var f;
for(f=0;f<heart.length;f++) {

hearts[f].addEventListener("click",function(){setCookie(f);});  

  }

  function setCookie(f){
    var d=new Date();
    d.setTime(d.getTime() + 365*24*60*60*1000);     
    var expires="expires="+d.toUTCString();
    document.cookie="product="+f+";"+domain=localhost+expires+";path=/"; 


  }
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Alex
  • 9
  • 3

1 Answers1

0

Noticed an error by myself.It is realy dumb,sorry for bothering you guys in for loop it should be hearths.length instead of hearth.length.

Alex
  • 9
  • 3
  • Note that it still won't do what you think it does because of how JS closures work. – Dave Newton Apr 16 '20 at 17:11
  • Well i still dont get it.I dont get why javascript add listener function doesnt pass actual f counter,but only passes when it finish loop last f. – Alex Apr 16 '20 at 17:46
  • Because by the time the callback runs `f` has already been incremented through its iteration. Closures capture the variable *itself*, not its value. See, e.g., https://stackoverflow.com/q/750486/438992, https://stackoverflow.com/q/46245591/438992, etc. – Dave Newton Apr 16 '20 at 18:01