How to Load JavaScript After Ajax in Magento 2

checkoutjavascriptmagento2payment-methodsrequirejs

I have a custom payment module and I am trying to show a message on the payment page using jQuery. My JS file is being called on the shipping page but not when the user clicks on the next step and the payment page is loaded. I am assuming that since it is already loaded it isn't looking for the div. If I shift-refresh on the payment page my JS loads but I cannot target a div ID. I am assuming because my JS runs before the page is loaded.

Here is my js:

define(
[
    'jquery'
],
  function($) {
    'use strict';

    $('document').ready(function(){
       if ( $('#payroll-form').attr('id') )  {
        alert("payment-form loaded");
       }
       alert("disabled loaded");
    });
});

The alert won't run in the if statement, but does outside of the if statement. How can I get this to load on the payment step and target the div after it gets rendered?

UPDATE

I am using this code:

define(
[
    'jquery'
],
  function($) {
    'use strict';

    jQuery('document').ready(function(){
        jQuery("#shipping-method-buttons-container button").click(function() {
           if ( jQuery('#checkout-payment-method-load').length && !jQuery('#payroll-form').length)  {
            jQuery('#checkout-payment-method-load').prepend('<div id="payroll-form">This is test message</div>');
           }
           alert("Clicked");
        });

        alert("new disabled");
    });
});

The alert "new disabled" loads on the shipping page. The alert "Clicked" does not show on the payment page when clicking on the Next button. Even if I remove the IF statement and leave in the alert "Click" does not show. All the ID's listed above are on the page. I can see the source file in the console. For some reason, it still doesn't work.

Best Answer

I've reviewed and I think you should call jquery on select shipping button click.

Please review the below example and it is working in default Magento setup.

define(['jquery'], function($) {
    'use strict';

    jQuery('document').ready(function(){
        jQuery("#shipping-method-buttons-container button").click(function() { 
           if ( jQuery('#checkout-payment-method-load').length && !jQuery('.message-alert-custom').length)  {
            jQuery('#checkout-payment-method-load').prepend('<div class="message-alert-custom">This is test message</div>');
           }
        });
    });
});

Hope this helps you.

Please let me know if you have any doubts.