When I use:
$(document).ready(function(){
});
Should my event listeners (e.g $('button').click(function(){})
go inside that doc.ready function or outside according to convention?
You should put anything in it that needs initialized AFTER the document object model is loaded. Including event listeners.
"Should my event listeners (e.g $('button').click(function(){}) go inside that doc.ready function or outside according to convention?"
HTML is interpreted from top to bottom so if your JS file is located in your head and you do not place it inside the .ready event then it will not be able to find your buttons since they haven't been generated yet.
If you put it inside your .ready event though, it is basically telling js to wait until the full dom object has been generated so the btn would then be found and bound.
On the other hand, there are people who strongly believe in including their js files at the very bottom of the page. Since HTML is interpreted from top to bottom then the js file will be loaded after the "meat" of the dom has been generated and you would not need to encapsulate your event binding inside .ready
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With