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>
Advertisement
Answer
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>