xms xms - 5 months ago 9
HTML Question

Calling addEventListener hundreds of times

Let's assume that I have hundreds of submit buttons on a HTML page. When a submit button is clicked, it calls a JavaScript function called TiedotNettiin which uses jQuery.post() for sending some information to the webserver.

Would it be a good idea to use JavaScript and its addEventListener hundreds of times on a HTML page? Does this require much system resources?

Or would it be better to set interval and run my JavaScript function TiedotNettiin, let's say, every 10 seconds? It would wait 10 seconds, collect all clicks within 10 seconds, make an array, and finally send that array with all new information to the server. This would happen in every 10 seconds instead of every submit button click.

Is there better alternatives?

Thanks for opinions and ideas.

Answer

No need for hundreds of event listeners when one delegated listener will suffice.

Make sure all the elements have same class and do

$(document).on('click', '.button-class', function(event){
  event.preventDefault();
  /* "this" is element event occured on */
  // do ajax with data relevant to this button

})
Comments