← All posts

JavaScript: click not working on dynamically added elements

Buttons loaded via AJAX or “load more” do not respond? Event delegation fixes it with a single listener.

JavaScript: click not working on dynamically added elements

Key points

  • addEventListener only applies to elements that exist when it is called.
  • Delegation puts one listener on a stable parent.
  • closest() finds the element actually clicked, even when an icon is inside.

The first posts open fine, but the ones added by the “Load more” button ignore clicks. The code is not broken: it simply ran before those elements existed.

Why it happens

document.querySelectorAll('.btn').forEach(b => b.addEventListener('click', …)) attaches listeners to the buttons present at that moment. Buttons inserted later by AJAX, a filter or a form get none.

The fix: event delegation

Clicks bubble up the document. So listen on a parent that always exists, then check what was clicked:

document.querySelector('.post-list').addEventListener('click', (e) => {
  const btn = e.target.closest('.js-like');
  if (!btn) return;
  e.preventDefault();
  toggleLike(btn.dataset.id);
});

closest() matters: if the button contains an SVG icon, e.target is the icon, not the button.

Why it is better

  • One listener instead of hundreds: less memory, especially on long lists.
  • Works for every future element, with nothing to re-attach after each load.
  • Code stays in one place and is easier to maintain.

Exceptions

Some events do not bubble (focus, blur, mouseenter). Use their bubbling versions: focusin, focusout, mouseover. And avoid listening on the whole document for high-frequency events like scroll or mousemove.

FAQ

What about jQuery?

Same idea: $(‘.post-list’).on(‘click’, ‘.js-like’, handler). Plain JavaScript now does it without a library.

Should I listen on document?

Pick the closest stable parent. document works, but then handles every click on the page.

Facing this on your site? We diagnose and fix it without putting your content at risk.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →