I’m just starting out with jQuery and want to use $(document).ready() to dynamically generate some HTML every time the page loads. It works fine when I use inline JavaScript code like this (this example is obviously simplified but it shows the behavior of the problem):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#container").html("<p>Hello world</p>");
});
</script>
<title>Test</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
However, if I link to an external JavaScript file and replace the inline JavaScript with this:
$(document).ready(start());
where the code for start is
function start(){
$("#container").html("<p>Hello world</p>");
}
nothing happens. I put an alert box in the external start() function and it pops up fine, so the code inside the function is being executed. The console also doesn’t show any errors. However, if I replace
$("#container").html("<p>Hello world</p>");
with
document.getElementById("container").innerHTML = "<p>Hello world</p>";
the console gives an error, saying document.getElementById(“container”) is null.
I’d really appreciate it if someone could point me in the right direction on this.
This part of your code:
should be:
So, in the first example, you’re calling
start()immediately before the document is ready and passing it’s return value to$(document).ready()which is NOT what you want.In the second example, you’re passing a reference to the
start()function to$(document).ready()and it will call thestart()function later when the document is ready which IS what you want.