<input type="button" onclick="alert('hello world');">
This is the way how inline events are handled. The main reason this is a bad idea is to clearly define the separation of concerns.
HTML - Structure of your page
JS - Your page functionality
This will cause less maintenance issues in the long run and when the system scales in size.
What happens if you have 100 buttons on your page and you want to remove the click event or change it for all of them. It would definitely be a nightmare.
Also you can only define a single event if you bind it inline.
By moving out to a separate file you have a lot of flexibility and you can just make a small change that will affect all the elements on the page.
So the 2nd approach is always better. and the way to go.
By defining the events like below
$('#clickme').on("click",function(){alert('hello world');});
you HTML
looks clean sans of any functionality and removes the tight coupling.
In the cases you have a dynamically added, it is true inline events always work but there is a concept called Event Delegation . You attach the event to a parent container that is always present on the page and bind the event to it. When the event occurs at a later time on the element , the event bubbles to the parent which handles the event for you.
For such cases you bind the events using .on
passing in a selector
$(document).on('click', '#clickme', function() {
Keep in mind that binding multiple events to a document is a bad idea. You can always use the closestStaticAncestor
to bind the events.