skip to Main Content

The below code works fine with jquery, however, when I try to convert the same to javascript using addEventListener, I don’t get the same output. Here is the jQuery code snippet:

    (function($){ 

        $( document.body ).on( 'added_to_cart', function(){
            console.log('EVENT: added_to_cart');
        });

    })(jQuery);

2

Answers


  1. Even shorter in JS:

    document.body.addEventListener('added_to_cart', function() {
        console.log('EVENT: added_to_cart');
    });
    setTimeout(function() {
        document.body.dispatchEvent(new CustomEvent('added_to_cart'));
    }, 3000);
    Login or Signup to reply.
  2. This will work. just create empty html file with script section and put this code there.

    // Equivalent of (function($) {})
    document.addEventListener('DOMContentLoaded', function(){
    
        // Equivalent of $(document.body).on('added_to_cart')
        document.body.addEventListener('added_to_cart', function() {
            console.log('EVENT: added_to_cart');
        });
    });
    
    // dispatching part
    setTimeout(function() {
        document.body.dispatchEvent(new CustomEvent('added_to_cart'));
    }, 3000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search