-2

I wanted to write a code, that stores some information in my local storage when I click on a button. The function for the local storage is working fine but the event listener doesn't. The click event is not referring to the button. It refers on every click.

        <td>
        <input type="button" value="In den Warenkorb"id="Knopfwarenkorb1">
       <script>
        const el = document.getElementById('Knopfwarenkorb1');
        el.addEventListener('click', zumWarenkorbHinzufuegen(produkt1));
       </script>
       </td>
deekeh
  • 675
  • 1
  • 6
  • 21
Erbas
  • 11
  • 3

2 Answers2

2

Use function instead of call event on load like:

let produkt1 = 'hello';
const el = document.getElementById('Knopfwarenkorb1');
el.addEventListener('click', () => {
  zumWarenkorbHinzufuegen(produkt1)
});

function zumWarenkorbHinzufuegen(pro){
  console.log(pro);
}
<td>
  <input type="button" value="In den Warenkorb" id="Knopfwarenkorb1">
</td>

As you can see in the example below the function will call without click

let produkt1 = 'hello';
const el = document.getElementById('Knopfwarenkorb1');
el.addEventListener('click', zumWarenkorbHinzufuegen(produkt1));

function zumWarenkorbHinzufuegen(pro){
  console.log(pro);
}
<td>
  <input type="button" value="In den Warenkorb" id="Knopfwarenkorb1">
</td>
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

You should add a reference to the method. Because otherwise the click will only execute what zumWarenkorbHinzufuegen is returning.

const el = document.getElementById('Knopfwarenkorb1');
el.addEventListener('click', knopfwarenkorb1Geclicked);

let produkt1 = {'it': 'worked'};

function knopfwarenkorb1Geclicked(event) {
  zumWarenkorbHinzufuegen(produkt1);
}

function zumWarenkorbHinzufuegen(prod1) {
  console.log(prod1);
}
<input type="button" value="In den Warenkorb" id="Knopfwarenkorb1">
Rickard Elimää
  • 7,107
  • 3
  • 14
  • 30