Anthony
Anthony

Reputation: 47

jQuery ().on Syntax

I'm making a gif search engine using the giphy api and jQuery. every time a topic is searched for, jQuery creates a topic button for the topic entered and loads in the respective gifs when said button is pressed. when loading in the gifs from the topic button. im confused why this works:

$(document).on("click", ".topic", displayGifs);

but this doesn't:

$(".topic").on('click', function(event) {
    displayGifs();
})

any help on this topic would be greatly appreciated

Upvotes: 0

Views: 199

Answers (1)

BenM
BenM

Reputation: 53208

The first sample delegates the event to the document object. Since that is a static element, any new elements that are added to the DOM which match the delegate selector (in this case .topic), the event binding will still trigger.

Your second example will only bind to elements that exist within the DOM at the time of binding.

Read more about event delegation in jQuery.

Upvotes: 4

Related Questions