Why jQuery .on() doesn't handle javascript dynamically created events?

Viewed 29

I have a vanilla Javascript system triggering a change event on a dropdown:

const event = new Event('change');
select.dispatchEvent(event);

It works perfectly handling the event through addEventListener() or $('select').on() but it doesn't work if .on() function is set to target dynamic elements:

$(document).on('change', 'select', function() {
    console.log('should');
});

What am I missing?

1 Answers

The default is for a constructed event to not bubble up the DOM tree. If you want that, you need to explicitly ask for it:

const event = new Event("change", { bubbles: true });

If the event doesn't bubble, it won't make it up to the document level and the delegated handler won't be invoked.

Related