0

ON the display page, I'm loading contents into a container div using ("#mydiv").load("myphpfile.php"); This works fine. My question is, how do I work with elements inside that loaded div?

Here is the code sample:

<div id="contents"></div>

<script type="text/javascript">
  $("#contents").load("___server_side.php");
  $("#message").click(function(){
    console.log('clicked');
  });
</script>

"#message" is an element in the loaded div. How do I access it and assign functions to it from the display page?

baby_yoda
  • 1
  • 1
  • What do you mean by "*active page*"? And when did you set this listener to the `#message` before or after the `.load` ? – Calvin Nunes Feb 27 '20 at 17:12
  • 1
    You would use [Event Delegation](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Turnip Feb 27 '20 at 17:14
  • Here is the code sample:
    #message is an element in the loaded div. How do I access it ?
    – baby_yoda Feb 27 '20 at 17:18
  • Welcome to Stack Overflow. Once the content is loaded, you can apply events like normal. If you want to before they are loaded, you can use `.on()`. – Twisty Feb 27 '20 at 17:22
  • Thanks guys. Assuming Twisty is correct, I can't get the code I posted above to work. Do you see an error in it? – baby_yoda Feb 27 '20 at 17:31

1 Answers1

0

You can use your code as is, yet I would add a .ready().

<div id="contents"></div>

<script type="text/javascript">
  $("#contents").load("___server_side.php");
  $("#message").ready(function(){
    $(this).click(function(){
      console.log('clicked');
    });
  });
</script>

Another option is to add the event callback once loading is finished.

<div id="contents"></div>

<script type="text/javascript">
  $("#contents").load("___server_side.php", function(){
    $("#message", this).click(function(){
      console.log('clicked');
    });
  });
</script>

Otherwise I would use the .on() option.

<script type="text/javascript">
  $("#contents").on("click", "#message", function(){
    console.log('clicked');
  });
  $("#contents").load("___server_side.php");
</script>

<div id="contents"></div>

See More:

Twisty
  • 30,304
  • 2
  • 26
  • 45
  • @baby_yoda Great! Once the element is `ready` then you can assign the callback. Without it, it may not have loaded to the DOM by the time you tried to assign it. – Twisty Feb 27 '20 at 17:35
  • @baby_yoda if it did help, I hope you want to upvote it or mark it as the answer. You may also want to take the Tour so you can know more about the site: https://stackoverflow.com/tour – Twisty Feb 27 '20 at 17:37