What is the JavaScript equivalent of the below jQuery code snippet?

Viewed 39

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

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);

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);

Related