A
A
artekha2016-11-30 13:27:14
JavaScript
artekha, 2016-11-30 13:27:14

How to hang events on added elements?

Hello. At the moment I am working on a social network (front-end), and there is a lot of js out there, which is hung up on certain elements on the page, for example, like a post, commenting, etc. But what to do about when records are added via ajax? After all, events will not be hung up on new elements. How can I track changes in the DOM and hang events on new elements? I write everything in native, so preferably without jQuery.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-11-30
@petermzg

No need to track changes, hang an event on the parent element, which is static.
For example:

$('body').on('click', '.comment .like', function(){ ... });

S
Seva, 2016-11-30
@Zewkin

Use delegation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question