WARNING:
THIS CODE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED; THE AUTHOR DISCLAIMS ALL LIABILITY FOR ANY DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR STORE DISRUPTIONS ARISING FROM ITS USE.
Scot Ranney • July 09, 2024
Detecting clicks on AJAX injected content must reference the parent element, not just the ID or CLASS that is being clicked.
In this case, the AJAX content is injected as HTML into the parent-element div. There are two lines of example AJAX content.
parent-element
<div id="parent-element"> <span class="some-class" data-something="This is something">Ajax content, Click Me 1</span> <span class="some-class" data-something="This is something else">Ajax content, Click Me 2</span> </div> <script> $("#parent-element").on('click', '.some-class', function(){ var $el = $(this); alert('something:' + $el.data('something')); }); </script>
In this case we are detecting a click on a class called some-class but it could also be an ID #some-class
some-class
#some-class
The alert will display whatever is in the data-something attribute.
data-something
ajax jquery