Consider the following html..
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<button id="mybutton" type="button">submit</button>
</body>
</html>
... when I try to implement a jQuery event handler in test.js for the click event of the button via...
$("#mybutton").on("click", function (event) {
alert("clicked");
});
... it does not work. But if I wrap the function with a document ready as in ...
$(document).ready(function () {
$("#mybutton").on("click", function (event) {
alert("clicked");
});
});
... it works. Why is that? Should all event handlers be placed in the document ready? Looking for a consistent approach.
I wish to utilize jQuery where possible. I have a difficult time understanding scope of functions with jQuery. I have seen some cases where people advocate placing the script definition in the html <head>
, where others have said to place at the bottom of the body for better scoping, but I clearly struggle to understand why.