I have a document that loads some content into a div with JQuery’s .load() function. That loaded content then tries to execute Javascript from the original document. This fails, possibly for obvious reasons (I am a Javascript novice). Here is simplified code that illustrates my problem.
test.html:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<style type="text/css">
div {
background: #ccc;
margin: 15px;
height: 500px;
width: 500px;
border: 1px solid #666;
}
</style>
</head>
<body>
<a href="#" class="loader">Load content into box below</a>
<div id="loadbox"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$('a.loader').click(function() {
$('#loadbox').load('loadme.html');
});
$('a.alerter').click(function() {
alert("I've been clicked!");
});
});
</script>
</body>
</html>
loadme.html:
<a href="#" class="alerter">Click me</a> for an alert.
The alert is triggered if I put the Javascript in the loaded content, but I have a large block of Javascript that I want to use with more than one div full of loaded content and I don’t want to keep loading the Javascript. Is there a way to access the Javascript in the original HTML from the loaded content? I don’t have a firm understanding of what order things are executed in, especially when I have loaded content into the page. Maybe this is my opportunity to learn! Thank you.
DYou should use live() or delegate() because you are adding an element to the document (this is for jQuery < 1.7)
for jQuery > 1.7 you should use on() and delegate the handler to the body