0

I have an add to cart button. When I click on it two things happen at the same time. The class b-items__item__add-to-cart and the onclick.

I would like the onclick to be able to be executed 2 seconds after pressing the add to cart button

With my code it does not work

<a style="cursor: pointer; margin-bottom: 5px;" data-nom="2001" data-prix="1.10" data-qte="1" data-checkbox="2001" data-url="https://phil.pecheperle.be/image-perles/perle-verre-peche-gardon-2001.JPG" class="btn btn-primary ajouter-panier b-items__item__add-to-cart" onclick="setTimeout(ouvreMaJolieAlert(event), 2000);">add to cart</a>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
phil
  • 3
  • 1
  • It's because you're invoking the function *immediately* then settings its return value to be executed after 2 seconds. You need to fix the syntax you use for `setTimeout()`. Check any of the duplicates I marked. Also note that using `onclick` is very bad practice and should be avoided. Use unobtrusive event handlers, eg. those bound by `addEventListener()`, instead – Rory McCrossan Oct 02 '22 at 19:15

1 Answers1

0

You're attempting to give the output of ouvreMaJolieAlert(event) to setTimeout as the callback. The function executes, but the output value of that function is probably nothing, or something else (depends on your specific scenario), meaning that the delayed invocation fails. You've probably meant to create a wrapper over it:

setTimeout(() => ouvreMaJolieAlert(event), 2000)

However, personally, I'd recommend you to create a function that handles this from a script; or better yet, use the addEventListener method:

document.querySelector("#the-id-of-your-link-here").addEventListener("click", () => {
   setTimeout(() => ouvreMaJolieAlert(event), 2000));
});

And if you're planning to create multiple links that will perform this action, you can just replace the ID with a class.

ascpixi
  • 529
  • 4
  • 13