Reputation: 5073
How do I trigger an event when a dynamically generated image is clicked?
<body>
<!-- this img element is dynamically generated after page load -->
<img class="youtube-thumb" src="//i.ytimg.com/vi/x-4KLOsfkHw/hqdefault.jpg">
</body>
I thought this would work:
$('body').delegate('.youtube-thumb').on('click', function(){
console.log('hi')
})
But this triggers the event when I click anywhere in the body
. What am I doing wrong?
Upvotes: 0
Views: 39
Reputation: 337714
Your usage of the delegate()
method is incorrect, try this:
$('body').delegate('.youtube-thumb', 'click', function(){
console.log('hi')
});
That said, you should be using on()
instead as delegate()
is considered outdated. Try this:
$('body').on('click', '.youtube-thumb', function(){
console.log('hi')
});
Upvotes: 3
Reputation: 20750
This should be like following. delegate()
function is not needed.
$('body').on('click', '.youtube-thumb', function(){
console.log('hi')
})
Upvotes: 0