简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM