In jQuery, to hang a handler on all the links on the page is enough of such code

$( "a" ).click(function() { alert( "Handler for .click() called." ); }); 

Moreover, if you dynamically add a new <a></a> element to the page, then the event will also work on hiring.

I want to understand how this is done. On pure JS it turns out like this:

 var a = d.getElementsByTagName("a"); for(var i = 0; i < a.length; i ++) { a[i].addEventListener("click", function (e) { alert( "Handler for .click() called." ); }); } 

But thus the event is hung up only on elements that already exist and if you add one more dynamically, there will be no event handler on it.

How to fix it? And how is this moment implemented in jQuery?

    2 answers 2

    The example described in the question

     $( "a" ).click(function() { alert( "Handler for .click() called." ); }); 

    just does not support event handling for dynamically added elements. For processing, you must use the functions:

      $('.container').delegate('a', 'click', function() { alert( "Handler for .click() called." ); }); 

    or

      $('.container').on('click', 'a', function() { alert( "Handler for .click() called." ); }); 

    In Javascript , to be honest, I don’t know whether similar methods exist. Alternatively, you can hang events directly when adding an item.

      This is called event delegation. To understand how this works, see this article: https://learn.javascript.ru/event-delegation

      In short, the point is, in the case of delegation, the event handler is hung on some root element, for example, on document. Further, as events float up, inside the handler, we check on which DOM node it occurred, and if the node suits us, then we perform the necessary action.

      Sample code from the article:

       table.onclick = function(event) { var target = event.target; // где был клик? if (target.tagName != 'TD') return; // не на TD? тогда не интересует highlight(target); // подсветить TD }; 

      On jQuery, of course, delegation is much easier to do than on pure JS. All this logic is under the hood.

      • Or you can add a sample code, for clarity =) - Dmitriy Simushev
      • No, I know how it works, I just thought that they had come up with something better. The fact is that my website is eating too many resources and at first I thought that this was due to the fact that all the events I had immediately assigned to the document. If someone met with such a problem, tell me how to handle it. - Stanislav Dalinin
      • @ StanislavDalinin too many handlers can of course lead to brakes, but if they did, they would, in any case, on the document, at least where. Most likely you have another problem. - IonDen