Let’s say I have markup like this:
<form action="foo">
<input name="bar" />
<button type="button">Save</button>
</form>
<script>
function baz() {
// Submit form via AJAX
}
</script>
Is it better to add this to the <button>:
onclick="baz()"
or to add this to the <script> (assuming jQuery):
$(function(){
$('button').on('click', baz);
});
I’ve seen much ado about best practices forbidding inline javascript, and I tend to agree. But I’m wondering if the manual wiring on document load/ready obfuscates what’s going on since it removes the context of said wiring that is present when onclick=”baz” is used.
Are there maintainability issues either way? Other pros/cons to either approach? My question at heart is what is the industry consensus on this particular aspect of using inline javascript (given that in general it’s not a good coding practice)?
The second way is considered better
It is referred to as Unobtrusive JavaScript where you separate the functionality/behavior from the page structure.