0

I have following code snippet in jquery when we click on layer 62 which loads a layer "loaded-page" from a page test.html as follows.

<script>
$(document).ready(function(){
$('#62').on('click', function(e) {

$("#62" ).load( "test.html #loaded-page" );

});

$('#loaded-page').on('click', function(e) {
alert('test');

 });
 }); 

 </script>

 <div id="62">Layer62</div>

Test page coding

 <div id="loaded-page">Loaded page</div>

MY issue is when we click on layer loaded-page inside DOM, the alert test is not functioning. Can anybody suggest a solution for this ? If needed I can prepare a fiddle for this

Tom
  • 500
  • 3
  • 5
  • 16

2 Answers2

1

This already has an answer, but essentially what you are looking for is event delegation

When you bind the event in your code, that element doesn't exist yet.

So, you bind the event differently, so that it will respond to dynamically added content:

$(document).on('click', '#loaded-page', function(e) {
    alert('test');
});

NOTE: Without knowing your html structure, I can't provide the best solution, but I CAN tell you that you do not want to use document if possible. Instead, you should use the nearest parent that exists when the DOM is initially loaded. In your case, my guess is that this would work:

$('#62').on('click', '#loaded-page', function(e) {
    alert('test');
});
Community
  • 1
  • 1
random_user_name
  • 25,694
  • 7
  • 76
  • 115
0

because that when you bind the

$('#loaded-page').on('click', function(e) {
    alert('test');
}); 

maybe that the #loaded-page element is not be loaded into the document,so can't find it the better way is :

$(document).delegate('#loaded-page','click',function(){
  alert('ok')

})