Magento 2, PHP

Magento 2: add custom javascript

Magento2 ship with most popular javascript library like Jquery, requireJS, KnockoutJS. I was trying to have my own custom javascript in way i was doing magento1 but it did not work magento2 it’s because of requireJS.

Today I am trying to show, how we can create a custom javascript and load using requireJS.

Lets create a custom js file following location.

Done/Js/view/frontend/web/js/custom.js
define([
    "jquery",
    "jquery/ui"
], function($) {
    "use strict";

    //creating jquery widget
    $.widget('mage.done', {
        _create: function() {
            console.log('hey, done is loaded!')
            //bind click event of elem id
            this.element.on('click', function(e){
                console.log('Click ME!')
            });
        }

    });

    return $.mage.done;
});
Tags :