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.
JavaScript
x
8
1
<td>
2
<input type="button" value="In den Warenkorb"id="Knopfwarenkorb1">
3
<script>
4
const el = document.getElementById('Knopfwarenkorb1');
5
el.addEventListener('click', zumWarenkorbHinzufuegen(produkt1));
6
</script>
7
</td>
8
Advertisement
Answer
Use function instead of call event on load like:
JavaScript
1
9
1
let produkt1 = 'hello';
2
const el = document.getElementById('Knopfwarenkorb1');
3
el.addEventListener('click', () => {
4
zumWarenkorbHinzufuegen(produkt1)
5
});
6
7
function zumWarenkorbHinzufuegen(pro){
8
console.log(pro);
9
}
JavaScript
1
3
1
<td>
2
<input type="button" value="In den Warenkorb" id="Knopfwarenkorb1">
3
</td>
As you can see in the example below the function will call without click
JavaScript
1
7
1
let produkt1 = 'hello';
2
const el = document.getElementById('Knopfwarenkorb1');
3
el.addEventListener('click', zumWarenkorbHinzufuegen(produkt1));
4
5
function zumWarenkorbHinzufuegen(pro){
6
console.log(pro);
7
}
JavaScript
1
3
1
<td>
2
<input type="button" value="In den Warenkorb" id="Knopfwarenkorb1">
3
</td>