0

The two files I'm using are below.

I click in "div2" which loads "divA" into "div1" as I'd expect. But after that, I try clicking "divA" which should load "divB", but it doesn't do anything

index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#div2").click(function(){
    $("#div1").load("load.php #divA");
  });
  $("#divA").click(function(){
    $("#divA").load("load.php #divB");
  });
});
</script>
<div id='div1'>
    <div id='div2'>click</div>
</div>

load.php

<div id='divA'>
    Click again
</div>

<div id='divB'>
    You clicked twice!
</div>

1 Answers1

0

AJAX is asynchronous, the new div isn't added yet when you try to add the click handler to it. Do it in the callback function of .load().

$(document).ready(function() {
  $("#div2").click(function() {
    $("#div1").load("load.php #divA", function() {
      $("#divA").click(function() {
        $("#divA").load("load.php #divB");
      });
    });
  });
});

Or use event delegation, as described in Event binding on dynamically created elements?

Barmar
  • 741,623
  • 53
  • 500
  • 612