I have been searching for what happens with javascript code when html page is rendered.
In my html page I have script that does (let say) two things. One is to open socket to Node.js server and listen for event user-list and the other task is to register event for button click.
First I tried like this:
var socket = io.connect(window.location.href);
socket.on("user-list", (data) => {
console.log("On no problem: " + JSON.stringify(data))
let str = "";
for(let i = 0; i < data.length; i++) {
str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
}
$("#private").text(str)
})
$("#submit-btn").click(function() {
let userName = $("#username").val(),
age = $("#age").val();
if( isNaN(age) ){
console.log("Age is NaN")
alert("Age must be a number!")
return;
}
$.post("user-data", {username: userName, age: age}, function(result) {
console.log(result);
})
})
But the button didn't work when clicked. Although, the socket connection worked well.
Then I tried to wrap the button click event registration in $(document).ready(function() {...}). like this:
var socket = io.connect(window.location.href);
socket.on("user-list", (data) => {
console.log("On no problem: " + JSON.stringify(data))
let str = "";
for(let i = 0; i < data.length; i++) {
str += "Name: " + data[i].name + " Age: " + data[i].age + " | ";
}
$("#private").text(str)
})
$(document).ready(function() {
$("#submit-btn").click(function() {
let userName = $("#username").val(),
age = $("#age").val();
if( isNaN(age) ){
console.log("Age is NaN")
alert("Age must be a number!")
return;
}
$.post("user-data", {username: userName, age: age}, function(result) {
console.log(result);
})
})
})
Now it works. I know that $(document).ready(function() is evoked when the document is loaded, but why isn't it working without that function?
And the other question is: Why the socket is still working although not wrapped by $(document).ready(function()?
In other words, why $("#submit-btn").click(function().... need $(document).ready(function()..... in order to work?