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.
<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
The alert will display whatever is in the data-something
attribute.