I have a reservation.js script which contains a function to add a event listener to a form input.
paymentInstalments.addEventListener('click', ()=> (...))
This function is being executed on page load thorough jquery's $(document).ready()
However this approach is proving cumbersome because when the page I'm trying to load does not have an id named "paymentInstalments" I get a TypeError "Cannot read property 'addEventListener' of null".
This happens obviously because the element i'm trying to add an event listener to does not exist in the html.
Thus, my question is: Shouldn't Webpack be smart enough to be able to understand when to execute a given import? Or its up to me to manage when scripts are executed?
Thanks a lot in advance :)
If you're attempting to interact with a DOM element before it actually exists in the DOM, you're going to run into this issue. Webpack can't help you with that.
If you want to add an event listener to an element and you're having trouble accessing it, try delegating the event to another element that you know will exist. Something like:
$('body').on('click', #paymentInstalments', function(e) {
// do stuff
});