0

I have a modal that is loaded via AJAX (I have no access to the JS files that trigger this).

I want to use JQuery to append some HTML to the body of the modal.

If course I can't simply do that within a document.ready function.

Is there a way to append the HTML when another element appears in the DOM?

I've tried

    $('.npopup .description').load(function(){
        $(this).append(message);
    });

and

    $('.npopup .description').ready(function(){
        $(this).append(message);
    });

with no results.

2
  • Depending on the library used to show the modal, there might be an event you can listen for. For example, Bootstrap has the shown.bs.modal event Commented Oct 9, 2020 at 5:08
  • after ajaxStop or ajaxComplete you can find element and if found, based on that you can append. Commented Oct 9, 2020 at 5:13

1 Answer 1

2

You may use the ajaxComplete() like that:

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "ajax/test.html" ) {
    $(this).append(message);
  }
});

Make sure you give a look at the event, xhr and settings to let you find what request you are interested in. Otherwise, if you don't use the if statement in the body of the callback, you will append the message in every ajax call.

Another possible solution is to listen for changes in the DOM using the MutationObserver. See for example here: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver.

The MutationObserver is a better solution though, but I don't remember what is the compatibility with the browsers. Generally speaking, the compatibility is quite good.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.