by Dave Reeder
1. September 2009 22:14
Imagine you want to grab text from a document and add it into a div on your page.
This is easily done with jQuery.
We start off with our HTML file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - load content into a div</title>
</head>
<body>
<div id="content"></div>
</body>
</html>
Notice we have put a div called "content" into the body. We will load content into this div.
Next we need to load our main jQuery file:
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
And finally we add our function to load the content over from the other file. Note, our other file is called "hello-world.html" and we use the document.ready() function to load the content when the page loads:
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#content").load("hello-world.html");
})
</script>
Our overall page is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - load content into a div</title>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#content").load("hello-world.html");
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
View a Demo Here