Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Trigger event when dynamically generated image is clicked

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

Answers (2)

Rory McCrossan
Rory McCrossan

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

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

This should be like following. delegate() function is not needed.

$('body').on('click', '.youtube-thumb', function(){
    console.log('hi')
})

Upvotes: 0

Related Questions