Reputation: 181
i have this main page
index.html
<script>
$(document).ready(function(){
$("#content").load('page.html');
$("#menu").click(function () {
alert('Hello');
});
});
<script>
<div id="content"></div>
and in page.html
<div id="menu">
<ul>
<li><a href="#">Link</a></li>
</ul>
</div>
the .load is working .. but the alert function is not working
must i but the function in page.html??? or there is another way ??
Upvotes: 2
Views: 91
Reputation: 10407
Since the element with the id of menu is being loaded you need to use on
<script>
$(document).ready(function(){
$("#content").load('page.html');
$(document).on('click', '#menu', function () {
alert('Hello');
});
});
<script>
<div id="content"></div>
Upvotes: 0
Reputation: 17061
Since the content is dynamically loaded, you need to use live()
(for jQuery <1.7) or on()
(1.7+).
These functions delegate events to dynamic elements along with ones that existed on page load.
Here's how it would look with on()
:
$(document).on("click", "#menu", function(){
alert("Menu clicked.")
});
Upvotes: 1
Reputation: 754545
The problem is your code to bind to #menu
runs before the sub-page is loaded. You need to either use on
or do the bind inside the call back which runs once the load completes
$(document).ready(function(){
$("#content").load('page.html', function() {
$("#menu").click(function () {
alert('Hello');
});
});
});
Version with on
$(document).ready(function(){
$('#content').load('page.html');
$('#content').on('click', '#menu', function() {
alert('Hello');
});
});
Upvotes: 2