Delegate jQuery event handlers when working with dynamic content. For more info see https://philkurth.com.au/tips/delegate-jquery-event-handlers-when-working-with-dynamic-content/
<div class="PostsGrid"> | |
<!-- This is our div containing our post items --> | |
<div class="PostsGrid__posts"> | |
<a href="#" class="PostsGrid__post"><!-- …Post grid item here… --></a> | |
<a href="#" class="PostsGrid__post"><!-- …Post grid item here… --></a> | |
<a href="#" class="PostsGrid__post"><!-- …Post grid item here… --></a> | |
</div> | |
<!-- A button to load more posts --> | |
<button class="PostsGrid__more">Load More Posts</button> | |
</div> |
// Shorthand for $( document ).ready() | |
$(function () { | |
// Bind a callback to the element that houses all post grid items. | |
// This event handler is bound on an element further up the DOM tree | |
// and instructed to target elements with the .PostsGrid__post class. | |
// This approach will work on any items that are dynamically added to | |
// the DOM, provided they are within the .PostsGrid__posts element. | |
$('.PostsGrid__posts').on('click', '.PostsGrid__post', function (event) { | |
// Handle click event. | |
}); | |
}); |
// Shorthand for $( document ).ready() | |
$(function () { | |
// Bind a callback to handle click events on all post grid items. | |
// This event handler is bound directly to each post grid item and | |
// will only work on items that were on the page when the handler | |
// was originally bound. | |
$('.PostsGrid__post').click(function (event) { | |
// Handle click event. | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment